Moved eth-common to eth

This commit is contained in:
Yuriy Glukhov 2019-02-05 12:10:36 +02:00
commit 1d6434883e
14 changed files with 896 additions and 0 deletions

86
.appveyor.yml Normal file
View File

@ -0,0 +1,86 @@
version: '{build}'
cache:
- x86_64-4.9.2-release-win32-seh-rt_v4-rev4.7z
- i686-4.9.2-release-win32-dwarf-rt_v4-rev4.7z
- Nim
matrix:
# We always want 32 and 64-bit compilation
fast_finish: false
platform:
- x86
- x64
install:
- setlocal EnableExtensions EnableDelayedExpansion
- IF "%PLATFORM%" == "x86" (
SET "MINGW_ARCHIVE=i686-4.9.2-release-win32-dwarf-rt_v4-rev4.7z" &
SET "MINGW_URL=https://sourceforge.net/projects/mingw-w64/files/Toolchains%%20targetting%%20Win32/Personal%%20Builds/mingw-builds/4.9.2/threads-win32/dwarf/i686-4.9.2-release-win32-dwarf-rt_v4-rev4.7z" &
SET "MINGW_DIR=mingw32"
) ELSE (
IF "%PLATFORM%" == "x64" (
SET "MINGW_ARCHIVE=x86_64-4.9.2-release-win32-seh-rt_v4-rev4.7z" &
SET "MINGW_URL=https://sourceforge.net/projects/mingw-w64/files/Toolchains%%20targetting%%20Win64/Personal%%20Builds/mingw-builds/4.9.2/threads-win32/seh/x86_64-4.9.2-release-win32-seh-rt_v4-rev4.7z" &
SET "MINGW_DIR=mingw64"
) else (
echo "Unknown platform"
)
)
- SET PATH=%CD%\%MINGW_DIR%\bin;%CD%\Nim\bin;%PATH%
# Unpack mingw
- IF NOT EXIST "%MINGW_ARCHIVE%" appveyor DownloadFile "%MINGW_URL%" -FileName "%MINGW_ARCHIVE%"
- 7z x -y "%MINGW_ARCHIVE%" > nul
# build nim from our own branch - this to avoid the day-to-day churn and
# regressions of the fast-paced Nim development while maintaining the
# flexibility to apply patches
- SET "NEED_REBUILD="
- IF NOT EXIST "Nim\\.git\\" (
git clone https://github.com/status-im/Nim.git
) ELSE (
( cd Nim ) &
( git pull ) &
( cd .. )
)
# Rebuild Nim if HEAD has moved or if we don't yet have a cached version
- IF NOT EXIST "Nim\\ver.txt" (
SET NEED_REBUILD=1
) ELSE (
( CD Nim ) &
( git rev-parse HEAD > ..\\cur_ver.txt ) &
( fc ver.txt ..\\cur_ver.txt || SET NEED_REBUILD=1 ) &
( cd .. )
)
- IF NOT EXIST "Nim\\bin\\nim.exe" SET NEED_REBUILD=1
- IF NOT EXIST "Nim\\bin\\nimble.exe" SET NEED_REBUILD=1
# after building nim, wipe csources to save on cache space
- IF DEFINED NEED_REBUILD (
cd Nim &
( IF EXIST "csources" rmdir /s /q csources ) &
git clone --depth 1 https://github.com/nim-lang/csources &
cd csources &
( IF "%PLATFORM%" == "x64" ( build64.bat ) else ( build.bat ) ) &
cd .. &
bin\nim c koch &
koch boot -d:release &
koch nimble &
git rev-parse HEAD > ver.txt &
rmdir /s /q csources
)
build_script:
- cd C:\projects\%APPVEYOR_PROJECT_SLUG%
- nimble install -y
test_script:
- nimble test
deploy: off

17
.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
# Ignore all files without extensions (unix executable files)
*
!*.*
!*/
!LICENSE*
nimcache/
# Executables shall be put in an ignored build/ directory
# Ignore dynamic, static libs and libtool archive files
build/
*.so
*.dylib
*.a
*.la
*.exe
*.dll

39
.travis.yml Normal file
View File

@ -0,0 +1,39 @@
language: c # or other C/C++ variants
sudo: false
# https://docs.travis-ci.com/user/caching/
#
# Caching the whole nim folder is better than relying on ccache - this way, we
# skip the expensive bootstrap process and linking
cache:
directories:
- nim
os:
- linux
- osx
install:
# build nim from our own branch - this to avoid the day-to-day churn and
# regressions of the fast-paced Nim development while maintaining the
# flexibility to apply patches
#
# check version of remote branch
- "export NIMVER=$(git ls-remote https://github.com/status-im/nim.git HEAD | cut -f 1)"
# after building nim, wipe csources to save on cache space
- "{ [ -f nim/$NIMVER/bin/nim ] && [ -f nim/$NIMVER/bin/nimble ] ; } ||
{ rm -rf nim ;
mkdir -p nim ;
git clone --depth=1 https://github.com/status-im/nim.git nim/$NIMVER ;
cd nim/$NIMVER ;
sh build_all.sh ;
rm -rf csources ;
cd ../.. ;
}"
- "export PATH=$PWD/nim/$NIMVER/bin:$PATH"
script:
- nimble install -y
- nimble test

204
LICENSE-APACHEv2 Normal file
View File

@ -0,0 +1,204 @@
Copyright (c) 2018 Status Research & Development GmbH
-----------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Status Research & Development GmbH
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

24
LICENSE-MIT Normal file
View File

@ -0,0 +1,24 @@
Copyright (c) 2018 Status Research & Development GmbH
-----------------------------------------------------
The MIT License (MIT)
Copyright (c) 2018 Status Research & Development GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

17
README.md Normal file
View File

@ -0,0 +1,17 @@
# eth - Eth Common Library
[![License: Apache](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
![Stability: experimental](https://img.shields.io/badge/stability-experimental-orange.svg)
## License
Licensed and distributed under either of
* MIT license: [LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT
or
* Apache License, Version 2.0, ([LICENSE-APACHEv2](LICENSE-APACHEv2) or http://www.apache.org/licenses/LICENSE-2.0)
at your option. This file may not be copied, modified, or distributed except according to those terms.

15
eth.nimble Normal file
View File

@ -0,0 +1,15 @@
version = "1.0.0"
author = "Status Research & Development GmbH"
description = "Ethereum Common library"
license = "MIT"
skipDirs = @["tests"]
requires "nim > 0.18.0",
"nimcrypto",
"ranges",
"stint",
"byteutils"
task test, "run tests":
cd "tests"
exec "nim c -r test_common"

2
eth/common.nim Normal file
View File

@ -0,0 +1,2 @@
import common / [eth_types, utils]
export eth_types, utils

379
eth/common/eth_types.nim Normal file
View File

@ -0,0 +1,379 @@
import
endians, options, times,
stint, nimcrypto, rlp, eth_trie/[defs, db]
export
stint, read, append, KeccakHash
type
Hash256* = MDigest[256]
EthTime* = Time
VMWord* = UInt256
BlockNonce* = array[8, byte]
AccountNonce* = uint64
Blob* = seq[byte]
BloomFilter* = array[256, byte]
EthAddress* = array[20, byte]
WhisperIdentity* = array[60, byte]
DifficultyInt* = UInt256
GasInt* = int64
## Type alias used for gas computation
# For reference - https://github.com/status-im/nimbus/issues/35#issuecomment-391726518
Topic* = array[32, byte]
# topic can be Hash256 or zero padded bytes array
Account* = object
nonce*: AccountNonce
balance*: UInt256
storageRoot*: Hash256
codeHash*: Hash256
Transaction* = object
accountNonce*: AccountNonce
gasPrice*: GasInt
gasLimit*: GasInt
to* {.rlpCustomSerialization.}: EthAddress
value*: UInt256
payload*: Blob
V*: byte
R*, S*: UInt256
isContractCreation* {.rlpIgnore.}: bool
TransactionStatus* = enum
Unknown,
Queued,
Pending,
Included,
Error
TransactionStatusMsg* = object
status*: TransactionStatus
data*: Blob
BlockNumber* = UInt256
BlockHeader* = object
parentHash*: Hash256
ommersHash*: Hash256
coinbase*: EthAddress
stateRoot*: Hash256
txRoot*: Hash256
receiptRoot*: Hash256
bloom*: BloomFilter
difficulty*: DifficultyInt
blockNumber*: BlockNumber
gasLimit*: GasInt
gasUsed*: GasInt
timestamp*: EthTime
extraData*: Blob
mixDigest*: Hash256
nonce*: BlockNonce
BlockBody* = object
transactions*: seq[Transaction]
uncles*: seq[BlockHeader]
Log* = object
address*: EthAddress
topics*: seq[Topic]
data*: Blob
HashOrStatus* = object
case isHash*: bool
of true:
hash*: Hash256
else:
status*: bool
Receipt* = object
stateRootOrStatus*: HashOrStatus
cumulativeGasUsed*: GasInt
bloom*: BloomFilter
logs*: seq[Log]
AccessList* = object
# XXX: Specify the structure of this
ShardTransaction* = object
chain*: uint
shard*: uint
to*: EthAddress
data*: Blob
gas*: GasInt
accessList*: AccessList
code*: Blob
salt*: Hash256
CollationHeader* = object
shard*: uint
expectedPeriod*: uint
periodStartPrevHash*: Hash256
parentHash*: Hash256
txRoot*: Hash256
coinbase*: EthAddress
stateRoot*: Hash256
receiptRoot*: Hash256
blockNumber*: BlockNumber
HashOrNum* = object
case isHash*: bool
of true:
hash*: Hash256
else:
number*: BlockNumber
BlocksRequest* = object
startBlock*: HashOrNum
maxResults*, skip*: uint
reverse*: bool
ProofRequest* = object
blockHash*: KeccakHash
accountKey*: Blob
key*: Blob
fromLevel*: uint
HeaderProofRequest* = object
chtNumber*: uint
blockNumber*: uint
fromLevel*: uint
ContractCodeRequest* = object
blockHash*: KeccakHash
key*: EthAddress
HelperTrieProofRequest* = object
subType*: uint
sectionIdx*: uint
key*: Blob
fromLevel*: uint
auxReq*: uint
AbstractChainDB* = ref object of RootRef
BlockHeaderRef* = ref BlockHeader
BlockBodyRef* = ref BlockBody
ReceiptRef* = ref Receipt
EthResourceRefs = BlockHeaderRef | BlockBodyRef | ReceiptRef
ValidationResult* {.pure.} = enum
OK
Error
when BlockNumber is int64:
## The goal of these templates is to make it easier to switch
## the block number type to a different representation
template vmWordToBlockNumber*(word: VMWord): BlockNumber =
BlockNumber(word.toInt)
template blockNumberToVmWord*(n: BlockNumber): VMWord =
u256(n)
template toBlockNumber*(n: SomeInteger): BlockNumber =
int64(n)
else:
template vmWordToBlockNumber*(word: VMWord): BlockNumber =
word
template blockNumberToVmWord*(n: BlockNumber): VMWord =
n
template toBlockNumber*(n: SomeInteger): BlockNumber =
u256(n)
proc toBlockNonce*(n: uint64): BlockNonce =
bigEndian64(addr result[0], unsafeAddr n)
proc toUint*(n: BlockNonce): uint64 =
bigEndian64(addr result, unsafeAddr n[0])
proc newAccount*(nonce: AccountNonce = 0, balance: UInt256 = 0.u256): Account =
result.nonce = nonce
result.balance = balance
result.storageRoot = emptyRlpHash
result.codeHash = blankStringHash
proc hashOrStatus*(hash: Hash256): HashOrStatus =
HashOrStatus(isHash: true, hash: hash)
proc hashOrStatus*(status: bool): HashOrStatus =
HashOrStatus(isHash: false, status: status)
proc hasStatus*(rec: Receipt): bool {.inline.} =
rec.stateRootOrStatus.isHash == false
proc hasStateRoot*(rec: Receipt): bool {.inline.} =
rec.stateRootOrStatus.isHash == true
proc stateRoot*(rec: Receipt): Hash256 {.inline.} =
assert(rec.hasStateRoot)
rec.stateRootOrStatus.hash
proc status*(rec: Receipt): int {.inline.} =
assert(rec.hasStatus)
if rec.stateRootOrStatus.status: 1 else: 0
#
# Rlp serialization:
#
proc read*(rlp: var Rlp, T: typedesc[StUint]): T {.inline.} =
if rlp.isBlob:
let bytes = rlp.toBytes
if bytes.len > 0:
result.initFromBytesBE(bytes.toOpenArray)
else:
result = 0.to(T)
else:
raise newException(RlpTypeMismatch, "Unsigned integer expected, but the source RLP is a list")
rlp.skipElem
proc append*(rlpWriter: var RlpWriter, value: StUint) =
if value > 128:
let bytes = value.toByteArrayBE
let nonZeroBytes = significantBytesBE(bytes)
rlpWriter.append bytes.toOpenArray(bytes.len - nonZeroBytes,
bytes.len - 1)
else:
rlpWriter.append(value.toInt)
proc read*(rlp: var Rlp, T: typedesc[Stint]): T {.inline.} =
# The Ethereum Yellow Paper defines the RLP serialization only
# for unsigned integers:
{.error: "RLP serialization of signed integers is not allowed".}
discard
proc append*(rlpWriter: var RlpWriter, value: Stint) =
# The Ethereum Yellow Paper defines the RLP serialization only
# for unsigned integers:
{.error: "RLP serialization of signed integers is not allowed".}
discard
proc read*(rlp: var Rlp, t: var Transaction, _: type EthAddress): EthAddress {.inline.} =
if rlp.blobLen != 0:
result = rlp.read(EthAddress)
else:
t.isContractCreation = true
rlp.skipElem()
proc append*(rlpWriter: var RlpWriter, t: Transaction, a: EthAddress) {.inline.} =
if t.isContractCreation:
rlpWriter.append("")
else:
rlpWriter.append(a)
proc read*(rlp: var Rlp, T: typedesc[HashOrStatus]): T {.inline.} =
assert(rlp.blobLen() == 32 or rlp.blobLen() == 1)
if rlp.blobLen == 1:
result = hashOrStatus(rlp.read(uint8) == 1)
else:
result = hashOrStatus(rlp.read(Hash256))
proc append*(rlpWriter: var RlpWriter, value: HashOrStatus) {.inline.} =
if value.isHash:
rlpWriter.append(value.hash)
else:
rlpWriter.append(if value.status: 1'u8 else: 0'u8)
proc read*(rlp: var Rlp, T: typedesc[Time]): T {.inline.} =
result = fromUnix(rlp.read(int64))
proc append*(rlpWriter: var RlpWriter, value: HashOrNum) =
case value.isHash
of true:
rlpWriter.append(value.hash)
else:
rlpWriter.append(value.number)
proc read*(rlp: var Rlp, T: typedesc[HashOrNum]): T =
if rlp.blobLen == 32:
result = HashOrNum(isHash: true, hash: rlp.read(Hash256))
else:
result = HashOrNum(isHash: false, number: rlp.read(UInt256))
proc append*(rlpWriter: var RlpWriter, t: Time) {.inline.} =
rlpWriter.append(t.toUnix())
proc rlpHash*[T](v: T): Hash256 =
keccak256.digest(rlp.encode(v))
func blockHash*(h: BlockHeader): KeccakHash {.inline.} = rlpHash(h)
proc notImplemented =
assert false, "Method not impelemented"
template hasData*(b: Blob): bool = b.len > 0
template hasData*(r: EthResourceRefs): bool = r != nil
template deref*(b: Blob): auto = b
template deref*(o: Option): auto = o.get
template deref*(r: EthResourceRefs): auto = r[]
method genesisHash*(db: AbstractChainDB): KeccakHash {.base, gcsafe.} =
notImplemented()
method getBlockHeader*(db: AbstractChainDB, b: HashOrNum, output: var BlockHeader): bool {.base, gcsafe.} =
notImplemented()
proc getBlockHeader*(db: AbstractChainDB, hash: KeccakHash): BlockHeaderRef {.gcsafe.} =
new result
if not db.getBlockHeader(HashOrNum(isHash: true, hash: hash), result[]):
return nil
proc getBlockHeader*(db: AbstractChainDB, b: BlockNumber): BlockHeaderRef {.gcsafe.} =
new result
if not db.getBlockHeader(HashOrNum(isHash: false, number: b), result[]):
return nil
method getBestBlockHeader*(self: AbstractChainDB): BlockHeader {.base, gcsafe.} =
notImplemented()
method getSuccessorHeader*(db: AbstractChainDB, h: BlockHeader, output: var BlockHeader): bool {.base, gcsafe.} =
notImplemented()
method getBlockBody*(db: AbstractChainDB, blockHash: KeccakHash): BlockBodyRef {.base, gcsafe.} =
notImplemented()
method getReceipt*(db: AbstractChainDB, hash: KeccakHash): ReceiptRef {.base, gcsafe.} =
notImplemented()
method getStateDb*(db: AbstractChainDB): TrieDatabaseRef {.base, gcsafe.} =
notImplemented()
method getCodeByHash*(db: AbstractChainDB, hash: KeccakHash): Blob {.base, gcsafe.} =
notImplemented()
method getSetting*(db: AbstractChainDb, key: string): Bytes {.base, gcsafe.} =
notImplemented()
method setSetting*(db: AbstractChainDb, key: string, val: openarray[byte]) {.base, gcsafe.} =
notImplemented()
method getHeaderProof*(db: AbstractChainDB, req: ProofRequest): Blob {.base, gcsafe.} =
notImplemented()
method getProof*(db: AbstractChainDB, req: ProofRequest): Blob {.base, gcsafe.} =
notImplemented()
method getHelperTrieProof*(db: AbstractChainDB, req: HelperTrieProofRequest): Blob {.base, gcsafe.} =
notImplemented()
method getTransactionStatus*(db: AbstractChainDB, txHash: KeccakHash): TransactionStatusMsg {.base, gcsafe.} =
notImplemented()
method addTransactions*(db: AbstractChainDB, transactions: openarray[Transaction]) {.base, gcsafe.} =
notImplemented()
method persistBlocks*(db: AbstractChainDB, headers: openarray[BlockHeader], bodies: openarray[BlockBody]): ValidationResult {.base, gcsafe.} =
notImplemented()

View File

@ -0,0 +1,39 @@
import
times,
json_serialization, nimcrypto/hash, eth_types
proc writeValue*(w: var JsonWriter, a: MDigest) {.inline.} =
w.writeValue $a
proc readValue*(r: var JsonReader, a: var MDigest) {.inline.} =
a = fromHex(type(a), r.readValue(string))
proc writeValue*(w: var JsonWriter, value: StUint) {.inline.} =
w.writeValue $value
proc readValue*(r: var JsonReader, value: var StUint) {.inline.} =
value = parse(r.readValue(string), type(value))
proc writeValue*(w: var JsonWriter, value: Stint) =
# The Ethereum Yellow Paper defines the RLP serialization only
# for unsigned integers:
{.error: "RLP serialization of signed integers is not allowed".}
discard
proc writeValue*(w: var JsonWriter, t: Time) {.inline.} =
w.writeValue t.toUnix()
proc readValue*(r: var JsonReader, t: var Time) {.inline.} =
t = fromUnix r.readValue(int)
# TODO: remove this once case object are fully supported
# by the serialization library
proc writeValue*(w: var JsonWriter, value: HashOrNum) =
w.beginRecord(HashOrNum)
w.writeField("isHash", value.isHash)
if value.isHash:
w.writeField("hash", value.hash)
else:
w.writeField("number", value.number)
w.endRecord()

View File

@ -0,0 +1,26 @@
import
eth_trie/[defs, db, hexary], rlp,
eth_types
proc getAccount*(db: TrieDatabaseRef,
rootHash: KeccakHash,
account: EthAddress): Account =
let trie = initSecureHexaryTrie(db, rootHash)
let data = trie.get(unnecessary_OpenArrayToRange account)
if data.len > 0:
result = rlp.decode(data, Account)
else:
result = newAccount()
proc getContractCode*(chain: AbstractChainDb, req: ContractCodeRequest): Blob {.gcsafe.} =
let b = chain.getBlockHeader(req.blockHash)
if b.hasData:
let acc = getAccount(chain.getStateDb, b.stateRoot, req.key)
result = chain.getCodeByHash(acc.codeHash)
proc getStorageNode*(chain: AbstractChainDb, hash: KeccakHash): Blob =
let db = chain.getStateDb
return db.get(hash.data)
# let trie = initSecureHexaryTrie(db, emptyRlpHash) # TODO emptyRlpHash is not correct here
# return trie.get(unnecessary_OpenArrayToRange hash.data)

10
eth/common/utils.nim Normal file
View File

@ -0,0 +1,10 @@
import nimcrypto, hashes, byteutils, eth_types
proc hash*(d: MDigest): Hash {.inline.} = hash(d.data)
proc parseAddress*(hexString: string): EthAddress =
hexToPaddedByteArray[20](hexString)
proc `$`*(a: EthAddress): string =
a.toHex()

2
tests/nim.cfg Normal file
View File

@ -0,0 +1,2 @@
--threads:on

36
tests/test_common.nim Normal file
View File

@ -0,0 +1,36 @@
import unittest, eth/common, rlp
proc `==`(a, b: HashOrStatus): bool =
result = a.isHash == b.isHash
if not result: return
if a.isHash:
result = result and a.hash == b.hash
else:
result = result and a.status == b.status
suite "rlp encoding":
test "receipt roundtrip":
var a, b, c, d: Receipt
var hash = rlpHash(a)
a.stateRootOrStatus = hashOrStatus(hash)
a.cumulativeGasUsed = 21000
a.logs = @[]
b.stateRootOrStatus = hashOrStatus(true)
b.cumulativeGasUsed = 52000
b.logs = @[]
var x = rlp.encode(a)
var y = rlp.encode(b)
c = x.decode(Receipt)
d = y.decode(Receipt)
check c == a
check d == b
check c.hasStateRoot
check c.stateRoot == hash
check d.hasStatus
check d.status == 1