2020-04-22 11:04:19 +00:00
|
|
|
import
|
|
|
|
randutils, stew/byteutils, random,
|
2020-04-28 09:58:16 +00:00
|
|
|
eth/[common, rlp], eth/trie/[hexary, db, trie_defs],
|
2020-04-28 02:30:10 +00:00
|
|
|
faststreams/input_stream, nimcrypto/[utils, sysrand],
|
2020-04-22 11:04:19 +00:00
|
|
|
../stateless/[witness_from_tree, tree_from_witness]
|
|
|
|
|
2020-04-28 09:58:16 +00:00
|
|
|
type
|
|
|
|
DB = TrieDatabaseRef
|
|
|
|
|
2020-04-28 02:30:10 +00:00
|
|
|
proc randU256(): UInt256 =
|
|
|
|
var bytes: array[32, byte]
|
|
|
|
discard randomBytes(bytes[0].addr, sizeof(result))
|
|
|
|
result = UInt256.fromBytesBE(bytes)
|
|
|
|
|
|
|
|
proc randNonce(): AccountNonce =
|
|
|
|
discard randomBytes(result.addr, sizeof(result))
|
|
|
|
|
2020-04-28 09:58:16 +00:00
|
|
|
proc randCode(db: DB): Hash256 =
|
|
|
|
if rand(0..1) == 0:
|
|
|
|
result = blankStringHash
|
|
|
|
else:
|
|
|
|
let codeLen = rand(1..150)
|
|
|
|
let code = randList(byte, rng(0, 255), codeLen, unique = false)
|
|
|
|
result = hexary.keccak(code)
|
|
|
|
db.put(result.data, code)
|
|
|
|
|
2020-04-28 02:30:10 +00:00
|
|
|
proc randHash(): Hash256 =
|
|
|
|
discard randomBytes(result.data[0].addr, sizeof(result))
|
|
|
|
|
2020-04-28 09:58:16 +00:00
|
|
|
proc randAccount(db: DB): Account =
|
2020-04-28 02:30:10 +00:00
|
|
|
result.nonce = randNonce()
|
|
|
|
result.balance = randU256()
|
2020-04-28 09:58:16 +00:00
|
|
|
result.codeHash = randCode(db)
|
2020-04-28 02:30:10 +00:00
|
|
|
result.storageRoot = randHash()
|
|
|
|
|
2020-04-28 09:58:16 +00:00
|
|
|
proc runTest(numPairs: int) =
|
2020-04-22 11:04:19 +00:00
|
|
|
var memDB = newMemoryDB()
|
2020-04-28 09:58:16 +00:00
|
|
|
var trie = initSecureHexaryTrie(memDB)
|
|
|
|
var addrs = newSeq[Bytes](numPairs)
|
2020-04-22 11:04:19 +00:00
|
|
|
|
|
|
|
for i in 0..<numPairs:
|
2020-04-28 09:58:16 +00:00
|
|
|
addrs[i] = randList(byte, rng(0, 255), 20, unique = false)
|
|
|
|
let acc = randAccount(memDB)
|
|
|
|
trie.put(addrs[i], rlp.encode(acc))
|
2020-04-22 11:04:19 +00:00
|
|
|
|
|
|
|
let rootHash = trie.rootHash
|
|
|
|
|
|
|
|
var wb = initWitnessBuilder(memDB, rootHash)
|
2020-04-28 09:58:16 +00:00
|
|
|
var witness = wb.getBranchRecurse(addrs[0])
|
2020-04-24 08:58:36 +00:00
|
|
|
var db = newMemoryDB()
|
2020-04-28 09:58:16 +00:00
|
|
|
when defined(useInputStream):
|
|
|
|
var input = memoryInput(witness)
|
|
|
|
var tb = initTreeBuilder(input, db)
|
|
|
|
else:
|
|
|
|
var tb = initTreeBuilder(witness, db)
|
2020-04-22 11:04:19 +00:00
|
|
|
var root = tb.treeNode()
|
|
|
|
debugEcho "root: ", root.data.toHex
|
|
|
|
debugEcho "rootHash: ", rootHash.data.toHex
|
|
|
|
doAssert root.data == rootHash.data
|
|
|
|
|
|
|
|
proc main() =
|
|
|
|
randomize()
|
2020-04-24 08:58:36 +00:00
|
|
|
|
2020-04-28 09:58:16 +00:00
|
|
|
for i in 0..<30:
|
|
|
|
runTest(rand(1..30))
|
2020-04-22 11:04:19 +00:00
|
|
|
|
|
|
|
main()
|