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.

351 lines
11 KiB

5 years ago
  1. package merkletree
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "strconv"
  6. "testing"
  7. "time"
  8. "github.com/dchest/uniuri"
  9. common3 "github.com/iden3/go-iden3/common"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/syndtr/goleveldb/leveldb"
  12. )
  13. type testBase struct {
  14. Length [4]byte
  15. Namespace Hash
  16. Type Hash
  17. Version uint32
  18. }
  19. type testLeaf struct {
  20. testBase
  21. extraIndex struct {
  22. Data []byte
  23. }
  24. }
  25. func parseTestLeafBytes(b []byte) testLeaf {
  26. var c testLeaf
  27. copy(c.testBase.Length[:], b[0:4])
  28. copy(c.testBase.Namespace[:], b[4:36])
  29. copy(c.testBase.Type[:], b[36:68])
  30. versionBytes := b[68:72]
  31. c.testBase.Version = common3.BytesToUint32(versionBytes)
  32. c.extraIndex.Data = b[72:]
  33. return c
  34. }
  35. func (c testLeaf) Bytes() (b []byte) {
  36. b = append(b, c.testBase.Length[:]...)
  37. b = append(b, c.testBase.Namespace[:]...)
  38. b = append(b, c.testBase.Type[:]...)
  39. versionBytes := common3.Uint32ToBytes(c.testBase.Version)
  40. b = append(b, versionBytes[:]...)
  41. b = append(b, c.extraIndex.Data[:]...)
  42. return b
  43. }
  44. func (c testLeaf) IndexLength() uint32 {
  45. return uint32(len(c.Bytes()))
  46. }
  47. func (c testLeaf) hi() Hash {
  48. h := HashBytes(c.Bytes())
  49. return h
  50. }
  51. func newTestLeaf(namespaceStr, typeStr string, data []byte) testLeaf {
  52. var c testLeaf
  53. c.testBase.Length = [4]byte{0x00, 0x00, 0x00, 0x48}
  54. c.testBase.Namespace = HashBytes([]byte(namespaceStr))
  55. c.testBase.Type = HashBytes([]byte(typeStr))
  56. c.testBase.Version = 0
  57. c.extraIndex.Data = data
  58. return c
  59. }
  60. type Fatalable interface {
  61. Fatal(args ...interface{})
  62. }
  63. func newTestingMerkle(f Fatalable, numLevels int) *MerkleTree {
  64. tim := time.Now().Unix()
  65. tstr := fmt.Sprint(tim)
  66. s := uniuri.New()
  67. db, err := leveldb.OpenFile("tmp/db"+s+"-"+tstr, nil)
  68. if err != nil {
  69. f.Fatal(err)
  70. return nil
  71. }
  72. // defer db.Close()
  73. mt, err := New(db, numLevels)
  74. if err != nil {
  75. f.Fatal(err)
  76. return nil
  77. }
  78. return mt
  79. }
  80. func TestNewMT(t *testing.T) {
  81. //create a new MT
  82. mt := newTestingMerkle(t, 140)
  83. defer mt.storage.Close()
  84. assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", mt.Root().Hex())
  85. }
  86. func TestAddLeaf(t *testing.T) {
  87. mt := newTestingMerkle(t, 140)
  88. defer mt.storage.Close()
  89. leaf := newTestLeaf("iden3.io", "typespec", []byte("c1"))
  90. assert.Equal(t, "0x939862c94ca9772fc9e2621df47128b1d4041b514e19edc969a92d8f0dae558f", leaf.hi().Hex())
  91. assert.Nil(t, mt.Add(leaf))
  92. assert.Equal(t, "0x9d3c407ff02c813cd474c0a6366b4f7c58bf417a38268f7a0d73a8bca2490b9b", mt.Root().Hex())
  93. }
  94. func TestAddLeafs(t *testing.T) {
  95. mt := newTestingMerkle(t, 140)
  96. defer mt.storage.Close()
  97. leaf := newTestLeaf("iden3.io", "typespec", []byte("c1"))
  98. assert.Equal(t, "0x939862c94ca9772fc9e2621df47128b1d4041b514e19edc969a92d8f0dae558f", leaf.hi().Hex())
  99. assert.Nil(t, mt.Add(leaf))
  100. assert.Nil(t, mt.Add(newTestLeaf("iden3.io2", "typespec2", []byte("c2"))))
  101. assert.Equal(t, "0xebae8fb483b48ba6c337136535198eb8bcf891daba40ac81e28958c09b9b229b", mt.Root().Hex())
  102. mt.Add(newTestLeaf("iden3.io3", "typespec3", []byte("c3")))
  103. mt.Add(newTestLeaf("iden3.io4", "typespec4", []byte("c4")))
  104. assert.Equal(t, "0xb4b51aa0c77a8e5ed0a099d7c11c7d2a9219ef241da84f0689da1f40a5f6ac31", mt.Root().Hex())
  105. }
  106. func TestAddLeafsCollision(t *testing.T) {
  107. mt := newTestingMerkle(t, 140)
  108. defer mt.storage.Close()
  109. leaf := newTestLeaf("iden3.io", "typespec", []byte("c1"))
  110. assert.Nil(t, mt.Add(leaf))
  111. root1 := mt.Root()
  112. assert.EqualError(t, mt.Add(leaf), ErrNodeAlreadyExists.Error())
  113. assert.Equal(t, root1.Hex(), mt.Root().Hex())
  114. }
  115. func TestAddLeafsDifferentOrders(t *testing.T) {
  116. mt1 := newTestingMerkle(t, 140)
  117. defer mt1.storage.Close()
  118. mt1.Add(newTestLeaf("iden3.io", "typespec", []byte("c1")))
  119. mt1.Add(newTestLeaf("iden3.io2", "typespec2", []byte("c2")))
  120. mt1.Add(newTestLeaf("iden3.io3", "typespec3", []byte("c3")))
  121. mt1.Add(newTestLeaf("iden3.io4", "typespec4", []byte("c4")))
  122. mt1.Add(newTestLeaf("iden3.io5", "typespec5", []byte("c5")))
  123. mt2 := newTestingMerkle(t, 140)
  124. defer mt2.storage.Close()
  125. mt2.Add(newTestLeaf("iden3.io3", "typespec3", []byte("c3")))
  126. mt2.Add(newTestLeaf("iden3.io2", "typespec2", []byte("c2")))
  127. mt2.Add(newTestLeaf("iden3.io", "typespec", []byte("c1")))
  128. mt2.Add(newTestLeaf("iden3.io4", "typespec4", []byte("c4")))
  129. mt2.Add(newTestLeaf("iden3.io5", "typespec5", []byte("c5")))
  130. assert.Equal(t, mt1.Root().Hex(), mt2.Root().Hex())
  131. }
  132. func TestBenchmarkAddingLeafs(t *testing.T) {
  133. mt := newTestingMerkle(t, 140)
  134. defer mt.storage.Close()
  135. start := time.Now()
  136. numToAdd := 1000
  137. for i := 0; i < numToAdd; i++ {
  138. leaf := newTestLeaf("iden3.io"+strconv.Itoa(i), "typespec"+strconv.Itoa(i), []byte("c"+strconv.Itoa(i)))
  139. mt.Add(leaf)
  140. }
  141. fmt.Print("time elapsed adding " + strconv.Itoa(numToAdd) + " leafs: ")
  142. fmt.Println(time.Since(start))
  143. }
  144. func BenchmarkAddingLeafs(b *testing.B) {
  145. mt := newTestingMerkle(b, 140)
  146. defer mt.storage.Close()
  147. b.ResetTimer()
  148. for i := 0; i < b.N; i++ {
  149. leaf := newTestLeaf("iden3.io"+strconv.Itoa(i), "typespec"+strconv.Itoa(i), []byte("c"+strconv.Itoa(i)))
  150. if err := mt.Add(leaf); err != nil {
  151. b.Fatal(err)
  152. }
  153. }
  154. }
  155. func TestGenerateProof(t *testing.T) {
  156. mt := newTestingMerkle(t, 140)
  157. defer mt.storage.Close()
  158. mt.Add(newTestLeaf("iden3.io_3", "typespec_3", []byte("c3")))
  159. mt.Add(newTestLeaf("iden3.io_2", "typespec_2", []byte("c2")))
  160. leaf1 := newTestLeaf("iden3.io_1", "typespec_1", []byte("c1"))
  161. assert.Nil(t, mt.Add(leaf1))
  162. mp, err := mt.GenerateProof(parseTestLeafBytes(leaf1.Bytes()).hi())
  163. assert.Nil(t, err)
  164. mpHexExpected := "0000000000000000000000000000000000000000000000000000000000000002beb0fd6dcf18d37fe51cf34beacd4c524d9c039ef9da2a27ccd3e7edf662c39c"
  165. assert.Equal(t, mpHexExpected, hex.EncodeToString(mp))
  166. }
  167. func TestCheckProof(t *testing.T) {
  168. mt := newTestingMerkle(t, 140)
  169. defer mt.storage.Close()
  170. leaf1 := newTestLeaf("iden3.io_1", "typespec_1", []byte("c1"))
  171. assert.Nil(t, mt.Add(leaf1))
  172. leaf3 := newTestLeaf("iden3.io_3", "typespec_3", []byte("c3"))
  173. assert.Nil(t, mt.Add(leaf3))
  174. mp, err := mt.GenerateProof(parseTestLeafBytes(leaf1.Bytes()).hi())
  175. assert.Nil(t, err)
  176. verified := CheckProof(mt.Root(), mp, leaf1.hi(), HashBytes(leaf1.Bytes()), mt.NumLevels())
  177. assert.True(t, verified)
  178. }
  179. func TestProofOfEmpty(t *testing.T) { // proof of a non revocated leaf, prove that is empty the hi position of the leaf.version+1
  180. mt := newTestingMerkle(t, 140)
  181. defer mt.storage.Close()
  182. leaf1 := newTestLeaf("iden3.io_1", "typespec_1", []byte("c1"))
  183. // proof when there is nothing in the tree
  184. mp, err := mt.GenerateProof(leaf1.hi())
  185. assert.Nil(t, err)
  186. verified := CheckProof(mt.Root(), mp, leaf1.hi(), EmptyNodeValue, mt.NumLevels())
  187. assert.True(t, verified)
  188. // add the first leaf
  189. assert.Nil(t, mt.Add(leaf1))
  190. // proof when there is only one leaf in the tree
  191. leaf2 := newTestLeaf("iden3.io_2", "typespec_2", []byte("c2"))
  192. mp, err = mt.GenerateProof(leaf2.hi())
  193. assert.Nil(t, err)
  194. verified = CheckProof(mt.Root(), mp, leaf2.hi(), EmptyNodeValue, mt.NumLevels())
  195. assert.True(t, verified)
  196. // check that the value in Hi is Empty
  197. valueInPos, err := mt.GetValueInPos(leaf2.hi())
  198. assert.Nil(t, err)
  199. assert.Equal(t, EmptyNodeValue.Bytes(), valueInPos)
  200. }
  201. func DifferentNonExistenceProofs(t *testing.T) {
  202. mt1 := newTestingMerkle(t, 140)
  203. defer mt1.storage.Close()
  204. mt2 := newTestingMerkle(t, 140)
  205. defer mt2.storage.Close()
  206. leaf1 := newTestLeaf("iden3.io_1", "typespec_1", []byte("c1"))
  207. leaf2 := newTestLeaf("iden3.io_1", "typespec_1", []byte("c2"))
  208. assert.Nil(t, mt1.Add(leaf1))
  209. assert.Nil(t, mt2.Add(leaf2))
  210. leaf1.Version++
  211. leaf2.Version++
  212. np1, err := mt1.GenerateProof(leaf1.hi())
  213. assert.Nil(t, err)
  214. np2, err := mt2.GenerateProof(leaf2.hi())
  215. assert.Nil(t, err)
  216. assert.True(t, CheckProof(mt1.Root(), np1, leaf1.hi(), EmptyNodeValue, mt1.NumLevels()))
  217. assert.True(t, CheckProof(mt2.Root(), np2, leaf2.hi(), EmptyNodeValue, mt2.NumLevels()))
  218. assert.Equal(t, "0000000000000000000000000000000000000000000000000000000000000010a40617c8c3390736831d00b2003e2133353190f5d3b3a586cf829f0f2009aacc", hex.EncodeToString(np1))
  219. assert.Equal(t, "0000000000000000000000000000000000000000000000000000000000000001b274a34a3bd95915fe982a0163e3e0a2f79a371b8307661341f8914e22b313e1", hex.EncodeToString(np2))
  220. }
  221. func TestGetLeafInPos(t *testing.T) {
  222. mt := newTestingMerkle(t, 140)
  223. defer mt.storage.Close()
  224. for i := 0; i < 50; i++ {
  225. leaf := newTestLeaf("iden3.io"+strconv.Itoa(i), "typespec"+strconv.Itoa(i), []byte("c"+strconv.Itoa(i)))
  226. mt.Add(leaf)
  227. }
  228. leaf1 := newTestLeaf("iden3.io_x", "typespec_x", []byte("cx"))
  229. assert.Nil(t, mt.Add(leaf1))
  230. leaf := parseTestLeafBytes(leaf1.Bytes())
  231. leafInPosBytes, err := mt.GetValueInPos(leaf.hi())
  232. assert.Nil(t, err)
  233. assert.Equal(t, leaf1.Bytes(), leafInPosBytes)
  234. // empty value in position
  235. leaf2 := newTestLeaf("iden3.io_y", "typespec_y", []byte("cy"))
  236. leafInPosBytes, err = mt.GetValueInPos(leaf2.hi())
  237. assert.Nil(t, err)
  238. assert.Equal(t, EmptyNodeValue[:], leafInPosBytes)
  239. }
  240. type vt struct {
  241. v []byte
  242. idxlen uint32
  243. }
  244. func (v vt) IndexLength() uint32 {
  245. return v.idxlen
  246. }
  247. func (v vt) Bytes() []byte {
  248. return v.v
  249. }
  250. func TestVector4(t *testing.T) {
  251. mt := newTestingMerkle(t, 4)
  252. defer mt.storage.Close()
  253. zeros := make([]byte, 32, 32)
  254. zeros[31] = 1 // to avoid adding Empty element
  255. assert.Nil(t, mt.Add(vt{zeros, uint32(1)}))
  256. v := vt{zeros, uint32(2)}
  257. assert.Nil(t, mt.Add(v))
  258. proof, _ := mt.GenerateProof(HashBytes(v.Bytes()[:v.IndexLength()]))
  259. assert.True(t, CheckProof(mt.Root(), proof, HashBytes(v.Bytes()[:v.IndexLength()]), HashBytes(v.Bytes()), mt.NumLevels()))
  260. assert.Equal(t, 4, mt.NumLevels())
  261. assert.Equal(t, "0000000000000000000000000000000000000000000000000000000000000001", hex.EncodeToString(v.Bytes()))
  262. assert.Equal(t, "0xc1b95ffbb999a6dd7a472a610a98891ffae95cc973d1d1e21acfdd68db830b51", mt.Root().Hex())
  263. assert.Equal(t, "00000000000000000000000000000000000000000000000000000000000000023cf025e4b4fc3ebe57374bf0e0c78ceb0009bdc4466a45174d80e8f508d1a4e3", hex.EncodeToString(proof))
  264. }
  265. func TestVector140(t *testing.T) {
  266. mt := newTestingMerkle(t, 140)
  267. defer mt.storage.Close()
  268. zeros := make([]byte, 32, 32)
  269. zeros[31] = 1 // to avoid adding Empty element
  270. for i := 1; i < len(zeros)-1; i++ {
  271. v := vt{zeros, uint32(i)}
  272. assert.Nil(t, mt.Add(v))
  273. proof, err := mt.GenerateProof(HashBytes(v.Bytes()[:v.IndexLength()]))
  274. assert.Nil(t, err)
  275. assert.True(t, CheckProof(mt.Root(), proof, HashBytes(v.Bytes()[:v.IndexLength()]), HashBytes(v.Bytes()), mt.NumLevels()))
  276. if i == len(zeros)-2 {
  277. assert.Equal(t, 140, mt.NumLevels())
  278. assert.Equal(t, uint32(30), v.IndexLength())
  279. assert.Equal(t, "0000000000000000000000000000000000000000000000000000000000000001", hex.EncodeToString(v.Bytes()))
  280. assert.Equal(t, "0x35f83288adf03bfb61d8d57fab9ed092da79833b58bbdbe9579b636753494ebd", mt.Root().Hex())
  281. assert.Equal(t, "000000000000000000000000000000000000000000000000000000000000001f0d1f363115f3333197a009b6674f46bba791308af220ad71515567702b3b44a2b540c1abad0ff81386a78b77e8907a56b7268d24513928ae83497adf4ad93a55e380267ead8305202da0640c1518e144dee87717c732b738fa182c6ef458defd6baf50022b01e3222715d4fca4c198e94536101f6ac314b3d261d3aaa0684395c1db60626e01c39fe4f69418055c2ebd70e0c07b6d9db5c4aed0a11ed2b6a773", hex.EncodeToString(proof))
  282. }
  283. }
  284. }