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.

526 lines
15 KiB

  1. package statedb
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io/ioutil"
  6. "math/big"
  7. "os"
  8. "strings"
  9. "testing"
  10. ethCommon "github.com/ethereum/go-ethereum/common"
  11. ethCrypto "github.com/ethereum/go-ethereum/crypto"
  12. "github.com/hermeznetwork/hermez-node/common"
  13. "github.com/hermeznetwork/hermez-node/log"
  14. "github.com/hermeznetwork/tracerr"
  15. "github.com/iden3/go-iden3-crypto/babyjub"
  16. "github.com/iden3/go-merkletree/db"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. )
  20. func newAccount(t *testing.T, i int) *common.Account {
  21. var sk babyjub.PrivateKey
  22. _, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
  23. require.NoError(t, err)
  24. pk := sk.Public()
  25. key, err := ethCrypto.GenerateKey()
  26. require.NoError(t, err)
  27. address := ethCrypto.PubkeyToAddress(key.PublicKey)
  28. return &common.Account{
  29. Idx: common.Idx(256 + i),
  30. TokenID: common.TokenID(i),
  31. Nonce: common.Nonce(i),
  32. Balance: big.NewInt(1000),
  33. PublicKey: pk.Compress(),
  34. EthAddr: address,
  35. }
  36. }
  37. func TestNewStateDBIntermediateState(t *testing.T) {
  38. dir, err := ioutil.TempDir("", "tmpdb")
  39. require.NoError(t, err)
  40. defer assert.NoError(t, os.RemoveAll(dir))
  41. sdb, err := NewStateDB(dir, 128, TypeTxSelector, 0)
  42. assert.NoError(t, err)
  43. // test values
  44. k0 := []byte("testkey0")
  45. k1 := []byte("testkey1")
  46. v0 := []byte("testvalue0")
  47. v1 := []byte("testvalue1")
  48. // store some data
  49. tx, err := sdb.db.DB().NewTx()
  50. assert.NoError(t, err)
  51. err = tx.Put(k0, v0)
  52. assert.NoError(t, err)
  53. err = tx.Commit()
  54. assert.NoError(t, err)
  55. v, err := sdb.db.DB().Get(k0)
  56. assert.NoError(t, err)
  57. assert.Equal(t, v0, v)
  58. // call NewStateDB which should get the db at the last checkpoint state
  59. // executing a Reset (discarding the last 'testkey0'&'testvalue0' data)
  60. sdb, err = NewStateDB(dir, 128, TypeTxSelector, 0)
  61. assert.NoError(t, err)
  62. v, err = sdb.db.DB().Get(k0)
  63. assert.NotNil(t, err)
  64. assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err))
  65. assert.Nil(t, v)
  66. // store the same data from the beginning that has ben lost since last NewStateDB
  67. tx, err = sdb.db.DB().NewTx()
  68. assert.NoError(t, err)
  69. err = tx.Put(k0, v0)
  70. assert.NoError(t, err)
  71. err = tx.Commit()
  72. assert.NoError(t, err)
  73. v, err = sdb.db.DB().Get(k0)
  74. assert.NoError(t, err)
  75. assert.Equal(t, v0, v)
  76. // make checkpoints with the current state
  77. bn, err := sdb.db.GetCurrentBatch()
  78. assert.NoError(t, err)
  79. assert.Equal(t, common.BatchNum(0), bn)
  80. err = sdb.db.MakeCheckpoint()
  81. assert.NoError(t, err)
  82. bn, err = sdb.db.GetCurrentBatch()
  83. assert.NoError(t, err)
  84. assert.Equal(t, common.BatchNum(1), bn)
  85. // write more data
  86. tx, err = sdb.db.DB().NewTx()
  87. assert.NoError(t, err)
  88. err = tx.Put(k1, v1)
  89. assert.NoError(t, err)
  90. err = tx.Commit()
  91. assert.NoError(t, err)
  92. v, err = sdb.db.DB().Get(k1)
  93. assert.NoError(t, err)
  94. assert.Equal(t, v1, v)
  95. // call NewStateDB which should get the db at the last checkpoint state
  96. // executing a Reset (discarding the last 'testkey1'&'testvalue1' data)
  97. sdb, err = NewStateDB(dir, 128, TypeTxSelector, 0)
  98. assert.NoError(t, err)
  99. bn, err = sdb.db.GetCurrentBatch()
  100. assert.NoError(t, err)
  101. assert.Equal(t, common.BatchNum(1), bn)
  102. v, err = sdb.db.DB().Get(k0)
  103. assert.NoError(t, err)
  104. assert.Equal(t, v0, v)
  105. v, err = sdb.db.DB().Get(k1)
  106. assert.NotNil(t, err)
  107. assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err))
  108. assert.Nil(t, v)
  109. }
  110. func TestStateDBWithoutMT(t *testing.T) {
  111. dir, err := ioutil.TempDir("", "tmpdb")
  112. require.NoError(t, err)
  113. defer assert.NoError(t, os.RemoveAll(dir))
  114. sdb, err := NewStateDB(dir, 128, TypeTxSelector, 0)
  115. assert.NoError(t, err)
  116. // create test accounts
  117. var accounts []*common.Account
  118. for i := 0; i < 4; i++ {
  119. accounts = append(accounts, newAccount(t, i))
  120. }
  121. // get non-existing account, expecting an error
  122. unexistingAccount := common.Idx(1)
  123. _, err = sdb.GetAccount(unexistingAccount)
  124. assert.NotNil(t, err)
  125. assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err))
  126. // add test accounts
  127. for i := 0; i < len(accounts); i++ {
  128. _, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
  129. assert.NoError(t, err)
  130. }
  131. for i := 0; i < len(accounts); i++ {
  132. existingAccount := accounts[i].Idx
  133. accGetted, err := sdb.GetAccount(existingAccount)
  134. assert.NoError(t, err)
  135. assert.Equal(t, accounts[i], accGetted)
  136. }
  137. // try already existing idx and get error
  138. existingAccount := common.Idx(256)
  139. _, err = sdb.GetAccount(existingAccount) // check that exist
  140. assert.NoError(t, err)
  141. _, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice
  142. assert.NotNil(t, err)
  143. assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err))
  144. // update accounts
  145. for i := 0; i < len(accounts); i++ {
  146. accounts[i].Nonce = accounts[i].Nonce + 1
  147. existingAccount = common.Idx(i)
  148. _, err = sdb.UpdateAccount(existingAccount, accounts[i])
  149. assert.NoError(t, err)
  150. }
  151. _, err = sdb.MTGetProof(common.Idx(1))
  152. assert.NotNil(t, err)
  153. assert.Equal(t, ErrStateDBWithoutMT, tracerr.Unwrap(err))
  154. }
  155. func TestStateDBWithMT(t *testing.T) {
  156. dir, err := ioutil.TempDir("", "tmpdb")
  157. require.NoError(t, err)
  158. defer assert.NoError(t, os.RemoveAll(dir))
  159. sdb, err := NewStateDB(dir, 128, TypeSynchronizer, 32)
  160. assert.NoError(t, err)
  161. // create test accounts
  162. var accounts []*common.Account
  163. for i := 0; i < 20; i++ {
  164. accounts = append(accounts, newAccount(t, i))
  165. }
  166. // get non-existing account, expecting an error
  167. _, err = sdb.GetAccount(common.Idx(1))
  168. assert.NotNil(t, err)
  169. assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err))
  170. // add test accounts
  171. for i := 0; i < len(accounts); i++ {
  172. _, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
  173. assert.NoError(t, err)
  174. }
  175. for i := 0; i < len(accounts); i++ {
  176. accGetted, err := sdb.GetAccount(accounts[i].Idx)
  177. assert.NoError(t, err)
  178. assert.Equal(t, accounts[i], accGetted)
  179. }
  180. // try already existing idx and get error
  181. _, err = sdb.GetAccount(common.Idx(256)) // check that exist
  182. assert.NoError(t, err)
  183. _, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice
  184. assert.NotNil(t, err)
  185. assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err))
  186. _, err = sdb.MTGetProof(common.Idx(256))
  187. assert.NoError(t, err)
  188. // update accounts
  189. for i := 0; i < len(accounts); i++ {
  190. accounts[i].Nonce = accounts[i].Nonce + 1
  191. _, err = sdb.UpdateAccount(accounts[i].Idx, accounts[i])
  192. assert.NoError(t, err)
  193. }
  194. a, err := sdb.GetAccount(common.Idx(256)) // check that account value has been updated
  195. assert.NoError(t, err)
  196. assert.Equal(t, accounts[0].Nonce, a.Nonce)
  197. }
  198. // TestCheckpoints performs almost the same test than kvdb/kvdb_test.go
  199. // TestCheckpoints, but over the StateDB
  200. func TestCheckpoints(t *testing.T) {
  201. dir, err := ioutil.TempDir("", "sdb")
  202. require.NoError(t, err)
  203. defer assert.NoError(t, os.RemoveAll(dir))
  204. sdb, err := NewStateDB(dir, 128, TypeSynchronizer, 32)
  205. assert.NoError(t, err)
  206. // create test accounts
  207. var accounts []*common.Account
  208. for i := 0; i < 10; i++ {
  209. accounts = append(accounts, newAccount(t, i))
  210. }
  211. // add test accounts
  212. for i := 0; i < len(accounts); i++ {
  213. _, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
  214. assert.NoError(t, err)
  215. }
  216. // do checkpoints and check that currentBatch is correct
  217. err = sdb.db.MakeCheckpoint()
  218. assert.NoError(t, err)
  219. cb, err := sdb.db.GetCurrentBatch()
  220. assert.NoError(t, err)
  221. assert.Equal(t, common.BatchNum(1), cb)
  222. for i := 1; i < 10; i++ {
  223. err = sdb.db.MakeCheckpoint()
  224. assert.NoError(t, err)
  225. cb, err = sdb.db.GetCurrentBatch()
  226. assert.NoError(t, err)
  227. assert.Equal(t, common.BatchNum(i+1), cb)
  228. }
  229. // printCheckpoints(t, sdb.path)
  230. // reset checkpoint
  231. err = sdb.Reset(3)
  232. assert.NoError(t, err)
  233. // check that reset can be repeated (as there exist the 'current' and
  234. // 'BatchNum3', from where the 'current' is a copy)
  235. err = sdb.Reset(3)
  236. require.NoError(t, err)
  237. // check that currentBatch is as expected after Reset
  238. cb, err = sdb.db.GetCurrentBatch()
  239. assert.NoError(t, err)
  240. assert.Equal(t, common.BatchNum(3), cb)
  241. // advance one checkpoint and check that currentBatch is fine
  242. err = sdb.db.MakeCheckpoint()
  243. assert.NoError(t, err)
  244. cb, err = sdb.db.GetCurrentBatch()
  245. assert.NoError(t, err)
  246. assert.Equal(t, common.BatchNum(4), cb)
  247. err = sdb.db.DeleteCheckpoint(common.BatchNum(1))
  248. assert.NoError(t, err)
  249. err = sdb.db.DeleteCheckpoint(common.BatchNum(2))
  250. assert.NoError(t, err)
  251. err = sdb.db.DeleteCheckpoint(common.BatchNum(1)) // does not exist, should return err
  252. assert.NotNil(t, err)
  253. err = sdb.db.DeleteCheckpoint(common.BatchNum(2)) // does not exist, should return err
  254. assert.NotNil(t, err)
  255. // Create a LocalStateDB from the initial StateDB
  256. dirLocal, err := ioutil.TempDir("", "ldb")
  257. require.NoError(t, err)
  258. defer assert.NoError(t, os.RemoveAll(dirLocal))
  259. ldb, err := NewLocalStateDB(dirLocal, 128, sdb, TypeBatchBuilder, 32)
  260. assert.NoError(t, err)
  261. // get checkpoint 4 from sdb (StateDB) to ldb (LocalStateDB)
  262. err = ldb.Reset(4, true)
  263. assert.NoError(t, err)
  264. // check that currentBatch is 4 after the Reset
  265. cb, err = ldb.db.GetCurrentBatch()
  266. assert.NoError(t, err)
  267. assert.Equal(t, common.BatchNum(4), cb)
  268. // advance one checkpoint in ldb
  269. err = ldb.db.MakeCheckpoint()
  270. assert.NoError(t, err)
  271. cb, err = ldb.db.GetCurrentBatch()
  272. assert.NoError(t, err)
  273. assert.Equal(t, common.BatchNum(5), cb)
  274. // Create a 2nd LocalStateDB from the initial StateDB
  275. dirLocal2, err := ioutil.TempDir("", "ldb2")
  276. require.NoError(t, err)
  277. defer assert.NoError(t, os.RemoveAll(dirLocal2))
  278. ldb2, err := NewLocalStateDB(dirLocal2, 128, sdb, TypeBatchBuilder, 32)
  279. assert.NoError(t, err)
  280. // get checkpoint 4 from sdb (StateDB) to ldb (LocalStateDB)
  281. err = ldb2.Reset(4, true)
  282. assert.NoError(t, err)
  283. // check that currentBatch is 4 after the Reset
  284. cb, err = ldb2.db.GetCurrentBatch()
  285. assert.NoError(t, err)
  286. assert.Equal(t, common.BatchNum(4), cb)
  287. // advance one checkpoint in ldb2
  288. err = ldb2.db.MakeCheckpoint()
  289. assert.NoError(t, err)
  290. cb, err = ldb2.db.GetCurrentBatch()
  291. assert.NoError(t, err)
  292. assert.Equal(t, common.BatchNum(5), cb)
  293. debug := false
  294. if debug {
  295. printCheckpoints(t, sdb.path)
  296. printCheckpoints(t, ldb.path)
  297. printCheckpoints(t, ldb2.path)
  298. }
  299. }
  300. func TestStateDBGetAccounts(t *testing.T) {
  301. dir, err := ioutil.TempDir("", "tmpdb")
  302. require.NoError(t, err)
  303. sdb, err := NewStateDB(dir, 128, TypeTxSelector, 0)
  304. assert.NoError(t, err)
  305. // create test accounts
  306. var accounts []common.Account
  307. for i := 0; i < 16; i++ {
  308. account := newAccount(t, i)
  309. accounts = append(accounts, *account)
  310. }
  311. // add test accounts
  312. for i := range accounts {
  313. _, err = sdb.CreateAccount(accounts[i].Idx, &accounts[i])
  314. require.NoError(t, err)
  315. }
  316. dbAccounts, err := sdb.GetAccounts()
  317. require.NoError(t, err)
  318. assert.Equal(t, accounts, dbAccounts)
  319. }
  320. func printCheckpoints(t *testing.T, path string) {
  321. files, err := ioutil.ReadDir(path)
  322. assert.NoError(t, err)
  323. fmt.Println(path)
  324. for _, f := range files {
  325. fmt.Println(" " + f.Name())
  326. }
  327. }
  328. func bigFromStr(h string, u int) *big.Int {
  329. if u == 16 {
  330. h = strings.TrimPrefix(h, "0x")
  331. }
  332. b, ok := new(big.Int).SetString(h, u)
  333. if !ok {
  334. panic("bigFromStr err")
  335. }
  336. return b
  337. }
  338. func TestCheckAccountsTreeTestVectors(t *testing.T) {
  339. dir, err := ioutil.TempDir("", "tmpdb")
  340. require.NoError(t, err)
  341. defer assert.NoError(t, os.RemoveAll(dir))
  342. sdb, err := NewStateDB(dir, 128, TypeSynchronizer, 32)
  343. require.NoError(t, err)
  344. ay0 := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(253), nil), big.NewInt(1))
  345. // test value from js version (compatibility-canary)
  346. assert.Equal(t, "1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", (hex.EncodeToString(ay0.Bytes())))
  347. bjjPoint0Comp := babyjub.PackSignY(true, ay0)
  348. bjj0 := babyjub.PublicKeyComp(bjjPoint0Comp)
  349. ay1 := bigFromStr("00", 16)
  350. bjjPoint1Comp := babyjub.PackSignY(false, ay1)
  351. bjj1 := babyjub.PublicKeyComp(bjjPoint1Comp)
  352. ay2 := bigFromStr("21b0a1688b37f77b1d1d5539ec3b826db5ac78b2513f574a04c50a7d4f8246d7", 16)
  353. bjjPoint2Comp := babyjub.PackSignY(false, ay2)
  354. bjj2 := babyjub.PublicKeyComp(bjjPoint2Comp)
  355. ay3 := bigFromStr("0x10", 16) // 0x10=16
  356. bjjPoint3Comp := babyjub.PackSignY(false, ay3)
  357. require.NoError(t, err)
  358. bjj3 := babyjub.PublicKeyComp(bjjPoint3Comp)
  359. accounts := []*common.Account{
  360. {
  361. Idx: 1,
  362. TokenID: 0xFFFFFFFF,
  363. PublicKey: bjj0,
  364. EthAddr: ethCommon.HexToAddress("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
  365. Nonce: common.Nonce(0xFFFFFFFFFF),
  366. Balance: bigFromStr("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16),
  367. },
  368. {
  369. Idx: 100,
  370. TokenID: 0,
  371. PublicKey: bjj1,
  372. EthAddr: ethCommon.HexToAddress("0x00"),
  373. Nonce: common.Nonce(0),
  374. Balance: bigFromStr("0", 10),
  375. },
  376. {
  377. Idx: 0xFFFFFFFFFFFF,
  378. TokenID: 3,
  379. PublicKey: bjj2,
  380. EthAddr: ethCommon.HexToAddress("0xA3C88ac39A76789437AED31B9608da72e1bbfBF9"),
  381. Nonce: common.Nonce(129),
  382. Balance: bigFromStr("42000000000000000000", 10),
  383. },
  384. {
  385. Idx: 10000,
  386. TokenID: 1000,
  387. PublicKey: bjj3,
  388. EthAddr: ethCommon.HexToAddress("0x64"),
  389. Nonce: common.Nonce(1900),
  390. Balance: bigFromStr("14000000000000000000", 10),
  391. },
  392. }
  393. for i := 0; i < len(accounts); i++ {
  394. _, err = accounts[i].HashValue()
  395. require.NoError(t, err)
  396. _, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
  397. if err != nil {
  398. log.Error(err)
  399. }
  400. require.NoError(t, err)
  401. }
  402. // root value generated by js version:
  403. assert.Equal(t, "17298264051379321456969039521810887093935433569451713402227686942080129181291", sdb.MT.Root().BigInt().String())
  404. }
  405. // TestListCheckpoints performs almost the same test than kvdb/kvdb_test.go
  406. // TestListCheckpoints, but over the StateDB
  407. func TestListCheckpoints(t *testing.T) {
  408. dir, err := ioutil.TempDir("", "tmpdb")
  409. require.NoError(t, err)
  410. defer assert.NoError(t, os.RemoveAll(dir))
  411. sdb, err := NewStateDB(dir, 128, TypeSynchronizer, 32)
  412. require.NoError(t, err)
  413. numCheckpoints := 16
  414. // do checkpoints
  415. for i := 0; i < numCheckpoints; i++ {
  416. err = sdb.db.MakeCheckpoint()
  417. require.NoError(t, err)
  418. }
  419. list, err := sdb.db.ListCheckpoints()
  420. require.NoError(t, err)
  421. assert.Equal(t, numCheckpoints, len(list))
  422. assert.Equal(t, 1, list[0])
  423. assert.Equal(t, numCheckpoints, list[len(list)-1])
  424. numReset := 10
  425. err = sdb.Reset(common.BatchNum(numReset))
  426. require.NoError(t, err)
  427. list, err = sdb.db.ListCheckpoints()
  428. require.NoError(t, err)
  429. assert.Equal(t, numReset, len(list))
  430. assert.Equal(t, 1, list[0])
  431. assert.Equal(t, numReset, list[len(list)-1])
  432. }
  433. // TestDeleteOldCheckpoints performs almost the same test than
  434. // kvdb/kvdb_test.go TestDeleteOldCheckpoints, but over the StateDB
  435. func TestDeleteOldCheckpoints(t *testing.T) {
  436. dir, err := ioutil.TempDir("", "tmpdb")
  437. require.NoError(t, err)
  438. defer assert.NoError(t, os.RemoveAll(dir))
  439. keep := 16
  440. sdb, err := NewStateDB(dir, keep, TypeSynchronizer, 32)
  441. require.NoError(t, err)
  442. numCheckpoints := 32
  443. // do checkpoints and check that we never have more than `keep`
  444. // checkpoints
  445. for i := 0; i < numCheckpoints; i++ {
  446. err = sdb.db.MakeCheckpoint()
  447. require.NoError(t, err)
  448. checkpoints, err := sdb.db.ListCheckpoints()
  449. require.NoError(t, err)
  450. assert.LessOrEqual(t, len(checkpoints), keep)
  451. }
  452. }