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.

515 lines
13 KiB

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
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
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
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
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
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
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
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
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
11 years ago
11 years ago
  1. /*
  2. This tree is not concurrency safe.
  3. If you want to use it from multiple goroutines, you need to wrap all calls to *IAVLTree
  4. with a mutex.
  5. */
  6. package merkle
  7. import (
  8. . "github.com/tendermint/tendermint/binary"
  9. "bytes"
  10. "io"
  11. "crypto/sha256"
  12. )
  13. const HASH_BYTE_SIZE int = 4+32
  14. // Immutable AVL Tree (wraps the Node root)
  15. type IAVLTree struct {
  16. db Db
  17. root *IAVLNode
  18. }
  19. func NewIAVLTree(db Db) *IAVLTree {
  20. return &IAVLTree{db:db, root:nil}
  21. }
  22. func NewIAVLTreeFromHash(db Db, hash ByteSlice) *IAVLTree {
  23. root := &IAVLNode{
  24. hash: hash,
  25. flags: IAVLNODE_FLAG_PERSISTED | IAVLNODE_FLAG_PLACEHOLDER,
  26. }
  27. root.fill(db)
  28. return &IAVLTree{db:db, root:root}
  29. }
  30. func (t *IAVLTree) Root() Node {
  31. return t.root
  32. }
  33. func (t *IAVLTree) Size() uint64 {
  34. if t.root == nil { return 0 }
  35. return t.root.Size()
  36. }
  37. func (t *IAVLTree) Height() uint8 {
  38. if t.root == nil { return 0 }
  39. return t.root.Height()
  40. }
  41. func (t *IAVLTree) Has(key Key) bool {
  42. if t.root == nil { return false }
  43. return t.root.has(t.db, key)
  44. }
  45. func (t *IAVLTree) Put(key Key, value Value) (updated bool) {
  46. if t.root == nil {
  47. t.root = NewIAVLNode(key, value)
  48. return false
  49. }
  50. t.root, updated = t.root.put(t.db, key, value)
  51. return updated
  52. }
  53. func (t *IAVLTree) Hash() (ByteSlice, uint64) {
  54. if t.root == nil { return nil, 0 }
  55. return t.root.Hash()
  56. }
  57. func (t *IAVLTree) Save() {
  58. if t.root == nil { return }
  59. if t.root.hash == nil {
  60. t.root.Hash()
  61. }
  62. t.root.Save(t.db)
  63. }
  64. func (t *IAVLTree) Get(key Key) (value Value) {
  65. if t.root == nil { return nil }
  66. return t.root.get(t.db, key)
  67. }
  68. func (t *IAVLTree) Remove(key Key) (value Value, err error) {
  69. if t.root == nil { return nil, NotFound(key) }
  70. newRoot, _, value, err := t.root.remove(t.db, key)
  71. if err != nil {
  72. return nil, err
  73. }
  74. t.root = newRoot
  75. return value, nil
  76. }
  77. func (t *IAVLTree) Copy() Tree {
  78. return &IAVLTree{db:t.db, root:t.root}
  79. }
  80. // Traverses all the nodes of the tree in prefix order.
  81. // return true from cb to halt iteration.
  82. // node.Height() == 0 if you just want a value node.
  83. func (t *IAVLTree) Traverse(cb func(Node) bool) {
  84. if t.root == nil { return }
  85. t.root.traverse(t.db, cb)
  86. }
  87. func (t *IAVLTree) Values() <-chan Value {
  88. root := t.root
  89. ch := make(chan Value)
  90. go func() {
  91. root.traverse(t.db, func(n Node) bool {
  92. if n.Height() == 0 { ch <- n.Value() }
  93. return true
  94. })
  95. close(ch)
  96. }()
  97. return ch
  98. }
  99. // Node
  100. type IAVLNode struct {
  101. key Key
  102. value Value
  103. size uint64
  104. height uint8
  105. hash ByteSlice
  106. left *IAVLNode
  107. right *IAVLNode
  108. // volatile
  109. flags byte
  110. }
  111. const (
  112. IAVLNODE_FLAG_PERSISTED = byte(0x01)
  113. IAVLNODE_FLAG_PLACEHOLDER = byte(0x02)
  114. )
  115. func NewIAVLNode(key Key, value Value) *IAVLNode {
  116. return &IAVLNode{
  117. key: key,
  118. value: value,
  119. size: 1,
  120. }
  121. }
  122. func (self *IAVLNode) Copy() *IAVLNode {
  123. if self.height == 0 {
  124. panic("Why are you copying a value node?")
  125. }
  126. return &IAVLNode{
  127. key: self.key,
  128. size: self.size,
  129. height: self.height,
  130. left: self.left,
  131. right: self.right,
  132. hash: nil,
  133. flags: byte(0),
  134. }
  135. }
  136. func (self *IAVLNode) Key() Key {
  137. return self.key
  138. }
  139. func (self *IAVLNode) Value() Value {
  140. return self.value
  141. }
  142. func (self *IAVLNode) Size() uint64 {
  143. return self.size
  144. }
  145. func (self *IAVLNode) Height() uint8 {
  146. return self.height
  147. }
  148. func (self *IAVLNode) has(db Db, key Key) (has bool) {
  149. if self.key.Equals(key) {
  150. return true
  151. }
  152. if self.height == 0 {
  153. return false
  154. } else {
  155. if key.Less(self.key) {
  156. return self.leftFilled(db).has(db, key)
  157. } else {
  158. return self.rightFilled(db).has(db, key)
  159. }
  160. }
  161. }
  162. func (self *IAVLNode) get(db Db, key Key) (value Value) {
  163. if self.height == 0 {
  164. if self.key.Equals(key) {
  165. return self.value
  166. } else {
  167. return nil
  168. }
  169. } else {
  170. if key.Less(self.key) {
  171. return self.leftFilled(db).get(db, key)
  172. } else {
  173. return self.rightFilled(db).get(db, key)
  174. }
  175. }
  176. }
  177. func (self *IAVLNode) Hash() (ByteSlice, uint64) {
  178. if self.hash != nil {
  179. return self.hash, 0
  180. }
  181. hasher := sha256.New()
  182. _, hashCount, err := self.saveToCountHashes(hasher, false)
  183. if err != nil { panic(err) }
  184. self.hash = hasher.Sum(nil)
  185. return self.hash, hashCount+1
  186. }
  187. func (self *IAVLNode) Save(db Db) {
  188. if self.hash == nil {
  189. panic("savee.hash can't be nil")
  190. }
  191. if self.flags & IAVLNODE_FLAG_PERSISTED > 0 ||
  192. self.flags & IAVLNODE_FLAG_PLACEHOLDER > 0 {
  193. return
  194. }
  195. // children
  196. if self.height > 0 {
  197. self.left.Save(db)
  198. self.right.Save(db)
  199. }
  200. // save self
  201. buf := bytes.NewBuffer(nil)
  202. _, err := self.WriteTo(buf)
  203. if err != nil { panic(err) }
  204. db.Put([]byte(self.hash), buf.Bytes())
  205. self.flags |= IAVLNODE_FLAG_PERSISTED
  206. }
  207. func (self *IAVLNode) put(db Db, key Key, value Value) (_ *IAVLNode, updated bool) {
  208. if self.height == 0 {
  209. if key.Less(self.key) {
  210. return &IAVLNode{
  211. key: self.key,
  212. height: 1,
  213. size: 2,
  214. left: NewIAVLNode(key, value),
  215. right: self,
  216. }, false
  217. } else if self.key.Equals(key) {
  218. return NewIAVLNode(key, value), true
  219. } else {
  220. return &IAVLNode{
  221. key: key,
  222. height: 1,
  223. size: 2,
  224. left: self,
  225. right: NewIAVLNode(key, value),
  226. }, false
  227. }
  228. } else {
  229. self = self.Copy()
  230. if key.Less(self.key) {
  231. self.left, updated = self.leftFilled(db).put(db, key, value)
  232. } else {
  233. self.right, updated = self.rightFilled(db).put(db, key, value)
  234. }
  235. if updated {
  236. return self, updated
  237. } else {
  238. self.calcHeightAndSize(db)
  239. return self.balance(db), updated
  240. }
  241. }
  242. }
  243. // newKey: new leftmost leaf key for tree after successfully removing 'key' if changed.
  244. func (self *IAVLNode) remove(db Db, key Key) (newSelf *IAVLNode, newKey Key, value Value, err error) {
  245. if self.height == 0 {
  246. if self.key.Equals(key) {
  247. return nil, nil, self.value, nil
  248. } else {
  249. return self, nil, nil, NotFound(key)
  250. }
  251. } else {
  252. if key.Less(self.key) {
  253. var newLeft *IAVLNode
  254. newLeft, newKey, value, err = self.leftFilled(db).remove(db, key)
  255. if err != nil {
  256. return self, nil, value, err
  257. } else if newLeft == nil { // left node held value, was removed
  258. return self.right, self.key, value, nil
  259. }
  260. self = self.Copy()
  261. self.left = newLeft
  262. } else {
  263. var newRight *IAVLNode
  264. newRight, newKey, value, err = self.rightFilled(db).remove(db, key)
  265. if err != nil {
  266. return self, nil, value, err
  267. } else if newRight == nil { // right node held value, was removed
  268. return self.left, nil, value, nil
  269. }
  270. self = self.Copy()
  271. self.right = newRight
  272. if newKey != nil {
  273. self.key = newKey
  274. newKey = nil
  275. }
  276. }
  277. self.calcHeightAndSize(db)
  278. return self.balance(db), newKey, value, err
  279. }
  280. }
  281. func (self *IAVLNode) WriteTo(w io.Writer) (n int64, err error) {
  282. n, _, err = self.saveToCountHashes(w, true)
  283. return
  284. }
  285. func (self *IAVLNode) saveToCountHashes(w io.Writer, meta bool) (n int64, hashCount uint64, err error) {
  286. var _n int64
  287. if meta {
  288. // height & size
  289. _n, err = UInt8(self.height).WriteTo(w)
  290. if err != nil { return } else { n += _n }
  291. _n, err = UInt64(self.size).WriteTo(w)
  292. if err != nil { return } else { n += _n }
  293. // key
  294. _n, err = Byte(GetBinaryType(self.key)).WriteTo(w)
  295. if err != nil { return } else { n += _n }
  296. _n, err = self.key.WriteTo(w)
  297. if err != nil { return } else { n += _n }
  298. }
  299. if self.height == 0 {
  300. // value
  301. _n, err = Byte(GetBinaryType(self.value)).WriteTo(w)
  302. if err != nil { return } else { n += _n }
  303. if self.value != nil {
  304. _n, err = self.value.WriteTo(w)
  305. if err != nil { return } else { n += _n }
  306. }
  307. } else {
  308. // left
  309. leftHash, leftCount := self.left.Hash()
  310. hashCount += leftCount
  311. _n, err = leftHash.WriteTo(w)
  312. if err != nil { return } else { n += _n }
  313. // right
  314. rightHash, rightCount := self.right.Hash()
  315. hashCount += rightCount
  316. _n, err = rightHash.WriteTo(w)
  317. if err != nil { return } else { n += _n }
  318. }
  319. return
  320. }
  321. // Given a placeholder node which has only the hash set,
  322. // load the rest of the data from db.
  323. // Not threadsafe.
  324. func (self *IAVLNode) fill(db Db) {
  325. if self.hash == nil {
  326. panic("placeholder.hash can't be nil")
  327. }
  328. buf := db.Get(self.hash)
  329. r := bytes.NewReader(buf)
  330. // node header
  331. self.height = uint8(ReadUInt8(r))
  332. self.size = uint64(ReadUInt64(r))
  333. // key
  334. key := ReadBinary(r)
  335. self.key = key.(Key)
  336. if self.height == 0 {
  337. // value
  338. self.value = ReadBinary(r)
  339. } else {
  340. // left
  341. var leftHash ByteSlice
  342. leftHash = ReadByteSlice(r)
  343. self.left = &IAVLNode{
  344. hash: leftHash,
  345. flags: IAVLNODE_FLAG_PERSISTED | IAVLNODE_FLAG_PLACEHOLDER,
  346. }
  347. // right
  348. var rightHash ByteSlice
  349. rightHash = ReadByteSlice(r)
  350. self.right = &IAVLNode{
  351. hash: rightHash,
  352. flags: IAVLNODE_FLAG_PERSISTED | IAVLNODE_FLAG_PLACEHOLDER,
  353. }
  354. if r.Len() != 0 {
  355. panic("buf not all consumed")
  356. }
  357. }
  358. self.flags &= ^IAVLNODE_FLAG_PLACEHOLDER
  359. }
  360. func (self *IAVLNode) leftFilled(db Db) *IAVLNode {
  361. if self.left.flags & IAVLNODE_FLAG_PLACEHOLDER > 0 {
  362. self.left.fill(db)
  363. }
  364. return self.left
  365. }
  366. func (self *IAVLNode) rightFilled(db Db) *IAVLNode {
  367. if self.right.flags & IAVLNODE_FLAG_PLACEHOLDER > 0 {
  368. self.right.fill(db)
  369. }
  370. return self.right
  371. }
  372. func (self *IAVLNode) rotateRight(db Db) *IAVLNode {
  373. self = self.Copy()
  374. sl := self.leftFilled(db).Copy()
  375. slr := sl.right
  376. sl.right = self
  377. self.left = slr
  378. self.calcHeightAndSize(db)
  379. sl.calcHeightAndSize(db)
  380. return sl
  381. }
  382. func (self *IAVLNode) rotateLeft(db Db) *IAVLNode {
  383. self = self.Copy()
  384. sr := self.rightFilled(db).Copy()
  385. srl := sr.left
  386. sr.left = self
  387. self.right = srl
  388. self.calcHeightAndSize(db)
  389. sr.calcHeightAndSize(db)
  390. return sr
  391. }
  392. func (self *IAVLNode) calcHeightAndSize(db Db) {
  393. self.height = maxUint8(self.leftFilled(db).Height(), self.rightFilled(db).Height()) + 1
  394. self.size = self.leftFilled(db).Size() + self.rightFilled(db).Size()
  395. }
  396. func (self *IAVLNode) calcBalance(db Db) int {
  397. return int(self.leftFilled(db).Height()) - int(self.rightFilled(db).Height())
  398. }
  399. func (self *IAVLNode) balance(db Db) (newSelf *IAVLNode) {
  400. balance := self.calcBalance(db)
  401. if (balance > 1) {
  402. if (self.leftFilled(db).calcBalance(db) >= 0) {
  403. // Left Left Case
  404. return self.rotateRight(db)
  405. } else {
  406. // Left Right Case
  407. self = self.Copy()
  408. self.left = self.leftFilled(db).rotateLeft(db)
  409. //self.calcHeightAndSize()
  410. return self.rotateRight(db)
  411. }
  412. }
  413. if (balance < -1) {
  414. if (self.rightFilled(db).calcBalance(db) <= 0) {
  415. // Right Right Case
  416. return self.rotateLeft(db)
  417. } else {
  418. // Right Left Case
  419. self = self.Copy()
  420. self.right = self.rightFilled(db).rotateRight(db)
  421. //self.calcHeightAndSize()
  422. return self.rotateLeft(db)
  423. }
  424. }
  425. // Nothing changed
  426. return self
  427. }
  428. func (self *IAVLNode) lmd(db Db) (*IAVLNode) {
  429. if self.height == 0 {
  430. return self
  431. }
  432. return self.leftFilled(db).lmd(db)
  433. }
  434. func (self *IAVLNode) rmd(db Db) (*IAVLNode) {
  435. if self.height == 0 {
  436. return self
  437. }
  438. return self.rightFilled(db).rmd(db)
  439. }
  440. func (self *IAVLNode) traverse(db Db, cb func(Node)bool) bool {
  441. stop := cb(self)
  442. if stop { return stop }
  443. if self.height > 0 {
  444. stop = self.leftFilled(db).traverse(db, cb)
  445. if stop { return stop }
  446. stop = self.rightFilled(db).traverse(db, cb)
  447. if stop { return stop }
  448. }
  449. return false
  450. }