You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

459 lines
12 KiB

10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package merkle
  2. import (
  3. "bytes"
  4. "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160"
  5. "io"
  6. "github.com/tendermint/tendermint/binary"
  7. . "github.com/tendermint/tendermint/common"
  8. )
  9. // Node
  10. type IAVLNode struct {
  11. key interface{}
  12. value interface{}
  13. height int8
  14. size int
  15. hash []byte
  16. leftHash []byte
  17. leftNode *IAVLNode
  18. rightHash []byte
  19. rightNode *IAVLNode
  20. persisted bool
  21. }
  22. func NewIAVLNode(key interface{}, value interface{}) *IAVLNode {
  23. return &IAVLNode{
  24. key: key,
  25. value: value,
  26. height: 0,
  27. size: 1,
  28. }
  29. }
  30. // NOTE: The hash is not saved or set. The caller should set the hash afterwards.
  31. // (Presumably the caller already has the hash)
  32. func ReadIAVLNode(t *IAVLTree, r io.Reader, n *int64, err *error) *IAVLNode {
  33. node := &IAVLNode{}
  34. // node header
  35. node.height = binary.ReadInt8(r, n, err)
  36. node.size = binary.ReadVarint(r, n, err)
  37. node.key = decodeByteSlice(t.keyCodec, r, n, err)
  38. if node.height == 0 {
  39. // value
  40. node.value = decodeByteSlice(t.valueCodec, r, n, err)
  41. } else {
  42. // children
  43. node.leftHash = binary.ReadByteSlice(r, n, err)
  44. node.rightHash = binary.ReadByteSlice(r, n, err)
  45. }
  46. return node
  47. }
  48. func (node *IAVLNode) _copy() *IAVLNode {
  49. if node.height == 0 {
  50. PanicSanity("Why are you copying a value node?")
  51. }
  52. return &IAVLNode{
  53. key: node.key,
  54. height: node.height,
  55. size: node.size,
  56. hash: nil, // Going to be mutated anyways.
  57. leftHash: node.leftHash,
  58. leftNode: node.leftNode,
  59. rightHash: node.rightHash,
  60. rightNode: node.rightNode,
  61. persisted: false, // Going to be mutated, so it can't already be persisted.
  62. }
  63. }
  64. func (node *IAVLNode) has(t *IAVLTree, key interface{}) (has bool) {
  65. if t.keyCodec.Compare(node.key, key) == 0 {
  66. return true
  67. }
  68. if node.height == 0 {
  69. return false
  70. } else {
  71. if t.keyCodec.Compare(key, node.key) < 0 {
  72. return node.getLeftNode(t).has(t, key)
  73. } else {
  74. return node.getRightNode(t).has(t, key)
  75. }
  76. }
  77. }
  78. func (node *IAVLNode) get(t *IAVLTree, key interface{}) (index int, value interface{}) {
  79. if node.height == 0 {
  80. if t.keyCodec.Compare(node.key, key) == 0 {
  81. return 0, node.value
  82. } else {
  83. return 0, nil
  84. }
  85. } else {
  86. if t.keyCodec.Compare(key, node.key) < 0 {
  87. return node.getLeftNode(t).get(t, key)
  88. } else {
  89. rightNode := node.getRightNode(t)
  90. index, value = rightNode.get(t, key)
  91. index += node.size - rightNode.size
  92. return index, value
  93. }
  94. }
  95. }
  96. func (node *IAVLNode) getByIndex(t *IAVLTree, index int) (key interface{}, value interface{}) {
  97. if node.height == 0 {
  98. if index == 0 {
  99. return node.key, node.value
  100. } else {
  101. PanicSanity("getByIndex asked for invalid index")
  102. return nil, nil
  103. }
  104. } else {
  105. // TODO: could improve this by storing the
  106. // sizes as well as left/right hash.
  107. leftNode := node.getLeftNode(t)
  108. if index < leftNode.size {
  109. return leftNode.getByIndex(t, index)
  110. } else {
  111. return node.getRightNode(t).getByIndex(t, index-leftNode.size)
  112. }
  113. }
  114. }
  115. // NOTE: sets hashes recursively
  116. func (node *IAVLNode) hashWithCount(t *IAVLTree) ([]byte, int) {
  117. if node.hash != nil {
  118. return node.hash, 0
  119. }
  120. hasher := ripemd160.New()
  121. buf := new(bytes.Buffer)
  122. _, hashCount, err := node.writeHashBytes(t, buf)
  123. if err != nil {
  124. PanicCrisis(err)
  125. }
  126. // fmt.Printf("Wrote IAVL hash bytes: %X\n", buf.Bytes())
  127. hasher.Write(buf.Bytes())
  128. node.hash = hasher.Sum(nil)
  129. // fmt.Printf("Write IAVL hash: %X\n", node.hash)
  130. return node.hash, hashCount + 1
  131. }
  132. // NOTE: sets hashes recursively
  133. func (node *IAVLNode) writeHashBytes(t *IAVLTree, w io.Writer) (n int64, hashCount int, err error) {
  134. // height & size
  135. binary.WriteInt8(node.height, w, &n, &err)
  136. binary.WriteVarint(node.size, w, &n, &err)
  137. // key is not written for inner nodes, unlike writePersistBytes
  138. if node.height == 0 {
  139. // key & value
  140. encodeByteSlice(node.key, t.keyCodec, w, &n, &err)
  141. encodeByteSlice(node.value, t.valueCodec, w, &n, &err)
  142. } else {
  143. // left
  144. if node.leftNode != nil {
  145. leftHash, leftCount := node.leftNode.hashWithCount(t)
  146. node.leftHash = leftHash
  147. hashCount += leftCount
  148. }
  149. if node.leftHash == nil {
  150. PanicSanity("node.leftHash was nil in writeHashBytes")
  151. }
  152. binary.WriteByteSlice(node.leftHash, w, &n, &err)
  153. // right
  154. if node.rightNode != nil {
  155. rightHash, rightCount := node.rightNode.hashWithCount(t)
  156. node.rightHash = rightHash
  157. hashCount += rightCount
  158. }
  159. if node.rightHash == nil {
  160. PanicSanity("node.rightHash was nil in writeHashBytes")
  161. }
  162. binary.WriteByteSlice(node.rightHash, w, &n, &err)
  163. }
  164. return
  165. }
  166. // NOTE: sets hashes recursively
  167. // NOTE: clears leftNode/rightNode recursively
  168. func (node *IAVLNode) save(t *IAVLTree) []byte {
  169. if node.hash == nil {
  170. node.hash, _ = node.hashWithCount(t)
  171. }
  172. if node.persisted {
  173. return node.hash
  174. }
  175. // save children
  176. if node.leftNode != nil {
  177. node.leftHash = node.leftNode.save(t)
  178. node.leftNode = nil
  179. }
  180. if node.rightNode != nil {
  181. node.rightHash = node.rightNode.save(t)
  182. node.rightNode = nil
  183. }
  184. // save node
  185. t.ndb.SaveNode(t, node)
  186. return node.hash
  187. }
  188. // NOTE: sets hashes recursively
  189. func (node *IAVLNode) writePersistBytes(t *IAVLTree, w io.Writer) (n int64, err error) {
  190. // node header
  191. binary.WriteInt8(node.height, w, &n, &err)
  192. binary.WriteVarint(node.size, w, &n, &err)
  193. // key (unlike writeHashBytes, key is written for inner nodes)
  194. encodeByteSlice(node.key, t.keyCodec, w, &n, &err)
  195. if node.height == 0 {
  196. // value
  197. encodeByteSlice(node.value, t.valueCodec, w, &n, &err)
  198. } else {
  199. // left
  200. if node.leftHash == nil {
  201. PanicSanity("node.leftHash was nil in writePersistBytes")
  202. }
  203. binary.WriteByteSlice(node.leftHash, w, &n, &err)
  204. // right
  205. if node.rightHash == nil {
  206. PanicSanity("node.rightHash was nil in writePersistBytes")
  207. }
  208. binary.WriteByteSlice(node.rightHash, w, &n, &err)
  209. }
  210. return
  211. }
  212. func (node *IAVLNode) set(t *IAVLTree, key interface{}, value interface{}) (newSelf *IAVLNode, updated bool) {
  213. if node.height == 0 {
  214. cmp := t.keyCodec.Compare(key, node.key)
  215. if cmp < 0 {
  216. return &IAVLNode{
  217. key: node.key,
  218. height: 1,
  219. size: 2,
  220. leftNode: NewIAVLNode(key, value),
  221. rightNode: node,
  222. }, false
  223. } else if cmp == 0 {
  224. return NewIAVLNode(key, value), true
  225. } else {
  226. return &IAVLNode{
  227. key: key,
  228. height: 1,
  229. size: 2,
  230. leftNode: node,
  231. rightNode: NewIAVLNode(key, value),
  232. }, false
  233. }
  234. } else {
  235. node = node._copy()
  236. if t.keyCodec.Compare(key, node.key) < 0 {
  237. node.leftNode, updated = node.getLeftNode(t).set(t, key, value)
  238. node.leftHash = nil
  239. } else {
  240. node.rightNode, updated = node.getRightNode(t).set(t, key, value)
  241. node.rightHash = nil
  242. }
  243. if updated {
  244. return node, updated
  245. } else {
  246. node.calcHeightAndSize(t)
  247. return node.balance(t), updated
  248. }
  249. }
  250. }
  251. // newHash/newNode: The new hash or node to replace node after remove.
  252. // newKey: new leftmost leaf key for tree after successfully removing 'key' if changed.
  253. // value: removed value.
  254. func (node *IAVLNode) remove(t *IAVLTree, key interface{}) (
  255. newHash []byte, newNode *IAVLNode, newKey interface{}, value interface{}, removed bool) {
  256. if node.height == 0 {
  257. if t.keyCodec.Compare(key, node.key) == 0 {
  258. return nil, nil, nil, node.value, true
  259. } else {
  260. return nil, node, nil, nil, false
  261. }
  262. } else {
  263. if t.keyCodec.Compare(key, node.key) < 0 {
  264. var newLeftHash []byte
  265. var newLeftNode *IAVLNode
  266. newLeftHash, newLeftNode, newKey, value, removed = node.getLeftNode(t).remove(t, key)
  267. if !removed {
  268. return nil, node, nil, value, false
  269. } else if newLeftHash == nil && newLeftNode == nil { // left node held value, was removed
  270. return node.rightHash, node.rightNode, node.key, value, true
  271. }
  272. node = node._copy()
  273. node.leftHash, node.leftNode = newLeftHash, newLeftNode
  274. node.calcHeightAndSize(t)
  275. return nil, node.balance(t), newKey, value, true
  276. } else {
  277. var newRightHash []byte
  278. var newRightNode *IAVLNode
  279. newRightHash, newRightNode, newKey, value, removed = node.getRightNode(t).remove(t, key)
  280. if !removed {
  281. return nil, node, nil, value, false
  282. } else if newRightHash == nil && newRightNode == nil { // right node held value, was removed
  283. return node.leftHash, node.leftNode, nil, value, true
  284. }
  285. node = node._copy()
  286. node.rightHash, node.rightNode = newRightHash, newRightNode
  287. if newKey != nil {
  288. node.key = newKey
  289. newKey = nil
  290. }
  291. node.calcHeightAndSize(t)
  292. return nil, node.balance(t), newKey, value, true
  293. }
  294. }
  295. }
  296. func (node *IAVLNode) getLeftNode(t *IAVLTree) *IAVLNode {
  297. if node.leftNode != nil {
  298. return node.leftNode
  299. } else {
  300. return t.ndb.GetNode(t, node.leftHash)
  301. }
  302. }
  303. func (node *IAVLNode) getRightNode(t *IAVLTree) *IAVLNode {
  304. if node.rightNode != nil {
  305. return node.rightNode
  306. } else {
  307. return t.ndb.GetNode(t, node.rightHash)
  308. }
  309. }
  310. func (node *IAVLNode) rotateRight(t *IAVLTree) *IAVLNode {
  311. node = node._copy()
  312. sl := node.getLeftNode(t)._copy()
  313. slrHash, slrCached := sl.rightHash, sl.rightNode
  314. sl.rightHash, sl.rightNode = nil, node
  315. node.leftHash, node.leftNode = slrHash, slrCached
  316. node.calcHeightAndSize(t)
  317. sl.calcHeightAndSize(t)
  318. return sl
  319. }
  320. func (node *IAVLNode) rotateLeft(t *IAVLTree) *IAVLNode {
  321. node = node._copy()
  322. sr := node.getRightNode(t)._copy()
  323. srlHash, srlCached := sr.leftHash, sr.leftNode
  324. sr.leftHash, sr.leftNode = nil, node
  325. node.rightHash, node.rightNode = srlHash, srlCached
  326. node.calcHeightAndSize(t)
  327. sr.calcHeightAndSize(t)
  328. return sr
  329. }
  330. // NOTE: mutates height and size
  331. func (node *IAVLNode) calcHeightAndSize(t *IAVLTree) {
  332. node.height = maxInt8(node.getLeftNode(t).height, node.getRightNode(t).height) + 1
  333. node.size = node.getLeftNode(t).size + node.getRightNode(t).size
  334. }
  335. func (node *IAVLNode) calcBalance(t *IAVLTree) int {
  336. return int(node.getLeftNode(t).height) - int(node.getRightNode(t).height)
  337. }
  338. func (node *IAVLNode) balance(t *IAVLTree) (newSelf *IAVLNode) {
  339. balance := node.calcBalance(t)
  340. if balance > 1 {
  341. if node.getLeftNode(t).calcBalance(t) >= 0 {
  342. // Left Left Case
  343. return node.rotateRight(t)
  344. } else {
  345. // Left Right Case
  346. node = node._copy()
  347. node.leftHash, node.leftNode = nil, node.getLeftNode(t).rotateLeft(t)
  348. //node.calcHeightAndSize()
  349. return node.rotateRight(t)
  350. }
  351. }
  352. if balance < -1 {
  353. if node.getRightNode(t).calcBalance(t) <= 0 {
  354. // Right Right Case
  355. return node.rotateLeft(t)
  356. } else {
  357. // Right Left Case
  358. node = node._copy()
  359. node.rightHash, node.rightNode = nil, node.getRightNode(t).rotateRight(t)
  360. //node.calcHeightAndSize()
  361. return node.rotateLeft(t)
  362. }
  363. }
  364. // Nothing changed
  365. return node
  366. }
  367. func (node *IAVLNode) traverse(t *IAVLTree, cb func(*IAVLNode) bool) bool {
  368. stop := cb(node)
  369. if stop {
  370. return stop
  371. }
  372. if node.height > 0 {
  373. stop = node.getLeftNode(t).traverse(t, cb)
  374. if stop {
  375. return stop
  376. }
  377. stop = node.getRightNode(t).traverse(t, cb)
  378. if stop {
  379. return stop
  380. }
  381. }
  382. return false
  383. }
  384. // Only used in testing...
  385. func (node *IAVLNode) lmd(t *IAVLTree) *IAVLNode {
  386. if node.height == 0 {
  387. return node
  388. }
  389. return node.getLeftNode(t).lmd(t)
  390. }
  391. // Only used in testing...
  392. func (node *IAVLNode) rmd(t *IAVLTree) *IAVLNode {
  393. if node.height == 0 {
  394. return node
  395. }
  396. return node.getRightNode(t).rmd(t)
  397. }
  398. //--------------------------------------------------------------------------------
  399. // Read a (length prefixed) byteslice then decode the object using the codec
  400. func decodeByteSlice(codec binary.Codec, r io.Reader, n *int64, err *error) interface{} {
  401. bytez := binary.ReadByteSlice(r, n, err)
  402. if *err != nil {
  403. return nil
  404. }
  405. n_ := new(int64)
  406. return codec.Decode(bytes.NewBuffer(bytez), n_, err)
  407. }
  408. // Encode object using codec, then write a (length prefixed) byteslice.
  409. func encodeByteSlice(o interface{}, codec binary.Codec, w io.Writer, n *int64, err *error) {
  410. buf, n_ := new(bytes.Buffer), new(int64)
  411. codec.Encode(o, buf, n_, err)
  412. if *err != nil {
  413. return
  414. }
  415. binary.WriteByteSlice(buf.Bytes(), w, n, err)
  416. }