Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdacea3aae | ||
|
|
be105a4744 | ||
|
|
161febc47a | ||
|
|
167cd2839c | ||
|
|
151a805b53 | ||
|
|
232cb1bcbf | ||
|
|
36c104f4db | ||
|
|
f144863b3b | ||
|
|
5dafc1fbc0 | ||
|
|
fb040d7484 | ||
|
|
60e951a172 | ||
|
|
9016be38a0 | ||
|
|
a17ace0187 | ||
|
|
5a623fa8d3 | ||
|
|
75c2c4c348 | ||
|
|
834930a498 | ||
|
|
0a92769bc5 | ||
|
|
8bcb2c312f | ||
|
|
2bb0b1aad6 | ||
|
|
4ddd3d0e20 | ||
|
|
07bd875752 | ||
|
|
f3379e33dd | ||
|
|
2ff4e95040 | ||
|
|
18a7f23173 | ||
|
|
ef1846f58c | ||
|
|
2eaa2c2262 | ||
|
|
bfb0447710 | ||
|
|
2c08f5594c | ||
|
|
253b1087bf | ||
|
|
8a3b6bf2ac | ||
|
|
b221bde694 | ||
|
|
2c41537636 | ||
|
|
d83b088c37 | ||
|
|
aca78f89b7 | ||
|
|
1788b899a4 | ||
|
|
1fe7a04af0 | ||
|
|
68ebdca6f9 | ||
|
|
5f7915649d | ||
|
|
f6df15cb38 | ||
|
|
03517a0eb4 | ||
|
|
54205d8787 | ||
|
|
8d8ff99d19 | ||
|
|
3054063942 | ||
|
|
54e181ca68 | ||
|
|
269333bb17 | ||
|
|
db532467cc | ||
|
|
ccdf9d91fc | ||
|
|
aea3decebf | ||
|
|
2db16d69da | ||
|
|
e3d694e63c | ||
|
|
2c0f3456f5 | ||
|
|
46cd8b1834 | ||
|
|
c0cd87ba6a | ||
|
|
2db235f244 | ||
|
|
a827c4a36b | ||
|
|
14b9c169bc | ||
|
|
a2772762e1 | ||
|
|
b1440d9673 | ||
|
|
67d8bced4f | ||
|
|
12f4810ced | ||
|
|
7a8d38c955 | ||
|
|
d09cd0afe6 | ||
|
|
bcca82eaa3 | ||
|
|
dad77b561d | ||
|
|
c939822a95 | ||
|
|
6d103cb1f1 | ||
|
|
99f84b6fe6 | ||
|
|
5b7f5feb1b | ||
|
|
7f8885f044 | ||
|
|
d235f3b84c | ||
|
|
1fdb8763ac | ||
|
|
cd5aee30c7 | ||
|
|
040638ca05 | ||
|
|
681e656034 | ||
|
|
85896f91b7 | ||
|
|
52c7f84432 | ||
|
|
aa6ee578f4 | ||
|
|
1f898f60c3 | ||
|
|
0c56037e1f | ||
|
|
9aa683442e | ||
|
|
adf3dd4b6f | ||
|
|
5ea4b6766a | ||
|
|
2c4fd6f099 | ||
|
|
f964b53fe3 | ||
|
|
b8dad6a09b | ||
|
|
1dc90d0417 | ||
|
|
784ffb8726 | ||
|
|
1ddffe65be | ||
|
|
fdeece4b5d | ||
|
|
a58b16b0a1 | ||
|
|
a99dcb4ca9 | ||
|
|
d3fd7ef532 | ||
|
|
3e8f5d34fb | ||
|
|
1df0e8b840 | ||
|
|
5bdec6bc41 | ||
|
|
9fbc07c836 | ||
|
|
cdcc3df9f2 | ||
|
|
5f6aec35b2 | ||
|
|
867f5c9971 | ||
|
|
257b16e184 | ||
|
|
b4a899cc8c | ||
|
|
4363bf5c07 | ||
|
|
7c19e86698 | ||
|
|
6ed1bc739d | ||
|
|
32724ff46c | ||
|
|
9a7ecf9ef3 | ||
|
|
ea4fb6222b | ||
|
|
1d10009678 | ||
|
|
feca7b67db | ||
|
|
edef920ae4 | ||
|
|
ec0fdb5215 | ||
|
|
040bc850f0 | ||
|
|
0c630b6e99 | ||
|
|
b68bd29304 | ||
|
|
c3b007de26 | ||
|
|
e9428ac208 | ||
|
|
9521bda9d0 | ||
|
|
9f76540c3a | ||
|
|
747c5f5400 | ||
|
|
3725006984 | ||
|
|
e08d31e242 | ||
|
|
0ff60a69da | ||
|
|
a99b1975e4 | ||
|
|
316926a6b5 | ||
|
|
15cb0b8e8c | ||
|
|
caa1938ce6 | ||
|
|
0d60752b8a | ||
|
|
1126466d51 | ||
|
|
76155a1516 | ||
|
|
01ce8b26b5 | ||
|
|
c5f2e209b4 | ||
|
|
6e604c3db6 | ||
|
|
0c2a9bc171 | ||
|
|
f35c5cf71e | ||
|
|
fe94c5a33c | ||
|
|
55a20ac15f | ||
|
|
eee4330bf4 | ||
|
|
5543a52472 | ||
|
|
db786ae3b0 | ||
|
|
d8a3177a20 | ||
|
|
fb54640823 | ||
|
|
731c986d75 | ||
|
|
30b481db24 | ||
|
|
dcdfb9a05a | ||
|
|
d78a503ba4 | ||
|
|
ddbb690ee6 | ||
|
|
bb5d5322d2 | ||
|
|
108a6f89f1 | ||
|
|
d9eb68b2d2 | ||
|
|
c5c230a2ea | ||
|
|
dcf8afb96c | ||
|
|
212bf4c4b2 | ||
|
|
a4a3ec1d7a | ||
|
|
efb334aef3 | ||
|
|
c83e8835ab | ||
|
|
728642afec | ||
|
|
5875d1ec82 | ||
|
|
8d6919ab2b | ||
|
|
abf72725ee | ||
|
|
8a55469403 | ||
|
|
a3857bffe4 | ||
|
|
3956081874 | ||
|
|
e1abb399cd | ||
|
|
3d00e3ed05 | ||
|
|
84fff0aa03 | ||
|
|
79cb508d83 | ||
|
|
f51d89e873 | ||
|
|
a7ae868dd8 | ||
|
|
ee59ff3650 | ||
|
|
8571f35031 | ||
|
|
f679082c3b | ||
|
|
aace7793ba | ||
|
|
b49e30d8e9 | ||
|
|
f207284e3a | ||
|
|
3d3e68c0ae | ||
|
|
66835c4c3e | ||
|
|
0d092cc535 | ||
|
|
a057940716 | ||
|
|
7dc6c52dec | ||
|
|
ca9d2a7bec | ||
|
|
072f035a02 | ||
|
|
5a35f84de3 | ||
|
|
0f81dc32d2 | ||
|
|
6a912eef41 | ||
|
|
88f2eaed7f |
@@ -0,0 +1,4 @@
|
||||
Dockerfile
|
||||
.git
|
||||
.gitea
|
||||
test
|
||||
@@ -0,0 +1,28 @@
|
||||
name: Publish Docker image
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
docker-build:
|
||||
name: Run docker build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- id: vars
|
||||
name: Output SHA and version tag
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA:0:7}" >> $GITHUB_OUTPUT
|
||||
echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
- name: Build and tag image
|
||||
run: |
|
||||
docker build . \
|
||||
-t cerc-io/eth-statediff-service \
|
||||
-t git.vdb.to/cerc-io/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}} \
|
||||
-t git.vdb.to/cerc-io/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.tag}}
|
||||
- name: Push image tags
|
||||
run: |
|
||||
echo ${{ secrets.GITEA_PUBLISH_TOKEN }} | docker login https://git.vdb.to -u cerccicd --password-stdin
|
||||
docker push git.vdb.to/cerc-io/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}}
|
||||
docker push git.vdb.to/cerc-io/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.tag}}
|
||||
@@ -0,0 +1,115 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: '*'
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- ci-test
|
||||
workflow_call:
|
||||
|
||||
env:
|
||||
ETH_TESTING_REF: v0.5.2
|
||||
|
||||
jobs:
|
||||
integration-tests:
|
||||
name: Run integration tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
check-latest: true
|
||||
- name: Run DB container
|
||||
run: docker compose -f test/compose.yml up --wait
|
||||
|
||||
- name: Build package
|
||||
run: go build .
|
||||
- name: Install test fixtures
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
repository: cerc-io/eth-testing
|
||||
path: ./fixtures
|
||||
ref: ${{ env.ETH_TESTING_REF }}
|
||||
# Run a sanity test against the fixture data
|
||||
# Complete integration tests are TODO
|
||||
- name: Run basic integration test
|
||||
env:
|
||||
ETHDB_PATH: ./fixtures/chains/data/premerge2/geth/chaindata
|
||||
ETH_CHAIN_CONFIG: ./fixtures/chains/data/premerge2/genesis.config.json
|
||||
ETH_GENESIS_BLOCK: 0x8a3c7cddacbd1ab4ec1b03805fa2a287f3a75e43d87f4f987fcc399f5c042614
|
||||
LOG_FILE: ./server-log
|
||||
timeout-minutes: 20
|
||||
run: |
|
||||
./eth-statediff-service --config ./test/ci-config.toml serve &
|
||||
sleep 10
|
||||
|
||||
./scripts/request-range.sh 0 10 || (E=$?; cat $LOG_FILE; exit $E)
|
||||
|
||||
until grep "Finished processing block 10" $LOG_FILE
|
||||
do sleep 1; done
|
||||
|
||||
count_results() {
|
||||
query="select count(*) from $1;"
|
||||
docker exec -e PGPASSWORD=password test-ipld-eth-db-1 \
|
||||
psql -tA cerc_testing -U vdbm -c "$query"
|
||||
}
|
||||
set -x
|
||||
[[ "$(count_results eth.header_cids)" = 11 ]]
|
||||
[[ "$(count_results eth.state_cids)" = 287 ]]
|
||||
[[ "$(count_results eth.storage_cids)" = 31 ]]
|
||||
[[ "$(count_results eth.transaction_cids)" = 144 ]]
|
||||
[[ "$(count_results eth.receipt_cids)" = 144 ]]
|
||||
|
||||
compliance-test:
|
||||
name: Run compliance tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
path: ./eth-statediff-service
|
||||
- uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version-file: ./eth-statediff-service/go.mod
|
||||
check-latest: true
|
||||
- name: Build current version
|
||||
working-directory: ./eth-statediff-service
|
||||
run: go build -o ../service-current .
|
||||
|
||||
- name: Checkout canonical version
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
path: ./eth-statediff-service-canonical
|
||||
ref: ${{ env.CANONICAL_VERSION }}
|
||||
- name: Build canonical version
|
||||
working-directory: ./eth-statediff-service-canonical
|
||||
run: go build -o ../service-canonical .
|
||||
|
||||
- name: Install test fixtures
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
repository: cerc-io/eth-testing
|
||||
path: ./fixtures
|
||||
ref: ${{ env.ETH_TESTING_REF }}
|
||||
- name: Run DB container
|
||||
working-directory: ./eth-statediff-service
|
||||
run: docker compose -f test/compose.yml up --wait
|
||||
- name: Compare statediff output
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
ETHDB_PATH: ./fixtures/chains/data/premerge2/geth/chaindata
|
||||
ETHDB_ANCIENT: ./fixtures/chains/data/premerge2/geth/chaindata/ancient
|
||||
ETH_CHAIN_CONFIG: ./fixtures/chains/data/premerge2/genesis.config.json
|
||||
ETH_GENESIS_BLOCK: "0x8a3c7cddacbd1ab4ec1b03805fa2a287f3a75e43d87f4f987fcc399f5c042614"
|
||||
run: |
|
||||
until
|
||||
ready_query='select max(version_id) from goose_db_version;'
|
||||
version=$(docker exec -e PGPASSWORD=password test-ipld-eth-db-1 \
|
||||
psql -tA cerc_testing -U vdbm -c "$ready_query")
|
||||
[[ "$version" -ge 21 ]]
|
||||
do sleep 1; done
|
||||
|
||||
./eth-statediff-service/scripts/compare-statediffs.sh \
|
||||
./service-canonical ./service-current
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Docker Compose Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Run docker build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Get the version
|
||||
id: vars
|
||||
run: echo ::set-output name=sha::$(echo ${GITHUB_SHA:0:7})
|
||||
- name: Run docker build
|
||||
run: make docker-build
|
||||
- name: Tag docker image
|
||||
run: docker tag vulcanize/eth-statediff-service docker.pkg.github.com/vulcanize/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}}
|
||||
- name: Docker Login
|
||||
run: echo ${{ secrets.GITHUB_TOKEN }} | docker login https://docker.pkg.github.com -u vulcanize --password-stdin
|
||||
- name: Docker Push
|
||||
run: docker push docker.pkg.github.com/vulcanize/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
name: Docker Build
|
||||
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Run docker build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Run docker build
|
||||
run: make docker-build
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Publish Docker image
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
jobs:
|
||||
push_to_registries:
|
||||
name: Push Docker image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get the version
|
||||
id: vars
|
||||
run: |
|
||||
echo ::set-output name=sha::$(echo ${GITHUB_SHA:0:7})
|
||||
echo ::set-output name=tag::$(echo ${GITHUB_REF#refs/tags/})
|
||||
- name: Docker Login to Github Registry
|
||||
run: echo ${{ secrets.GITHUB_TOKEN }} | docker login https://docker.pkg.github.com -u vulcanize --password-stdin
|
||||
- name: Docker Pull
|
||||
run: docker pull docker.pkg.github.com/vulcanize/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}}
|
||||
- name: Docker Login to Docker Registry
|
||||
run: echo ${{ secrets.VULCANIZEJENKINS_PAT }} | docker login -u vulcanizejenkins --password-stdin
|
||||
- name: Tag docker image
|
||||
run: docker tag docker.pkg.github.com/vulcanize/eth-statediff-service/eth-statediff-service:${{steps.vars.outputs.sha}} vulcanize/eth-statediff-service:${{steps.vars.outputs.tag}}
|
||||
- name: Docker Push to Docker Hub
|
||||
run: docker push vulcanize/eth-statediff-service:${{steps.vars.outputs.tag}}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
.idea/
|
||||
eth-statediff-service
|
||||
.vscode
|
||||
|
||||
+22
-19
@@ -1,33 +1,36 @@
|
||||
FROM golang:1.13-alpine as builder
|
||||
FROM golang:1.21-alpine as builder
|
||||
|
||||
RUN apk --update --no-cache add make git g++ linux-headers
|
||||
RUN apk add --no-cache git gcc musl-dev binutils-gold
|
||||
# DEBUG
|
||||
RUN apk add busybox-extras
|
||||
|
||||
# Get and build ipfs-blockchain-watcher
|
||||
ADD . /go/src/github.com/vulcanize/eth-statediff-service
|
||||
WORKDIR /go/src/github.com/vulcanize/eth-statediff-service
|
||||
RUN GO111MODULE=on GCO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o eth-statediff-service .
|
||||
WORKDIR /eth-statediff-service
|
||||
|
||||
ARG GIT_VDBTO_TOKEN
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN if [ -n "$GIT_VDBTO_TOKEN" ]; then git config --global url."https://$GIT_VDBTO_TOKEN:@git.vdb.to/".insteadOf "https://git.vdb.to/"; fi && \
|
||||
go mod download && \
|
||||
rm -f ~/.gitconfig
|
||||
COPY . .
|
||||
|
||||
RUN go build -ldflags '-extldflags "-static"' -o eth-statediff-service .
|
||||
|
||||
# app container
|
||||
FROM alpine
|
||||
|
||||
ARG USER="vdm"
|
||||
ARG CONFIG_FILE="./environments/example.toml"
|
||||
ARG USER="vdbm"
|
||||
ARG EXPOSE_PORT=8545
|
||||
RUN adduser -Du 5000 $USER
|
||||
WORKDIR /app
|
||||
RUN chown $USER /app
|
||||
USER $USER
|
||||
ARG CONFIG_FILE="./environments/docker.toml"
|
||||
|
||||
# chown first so dir is writable
|
||||
# note: using $USER is merged, but not in the stable release yet
|
||||
COPY --chown=5000:5000 --from=builder /go/src/github.com/vulcanize/eth-statediff-service/$CONFIG_FILE config.toml
|
||||
COPY --chown=5000:5000 --from=builder /go/src/github.com/vulcanize/eth-statediff-service/startup_script.sh .
|
||||
COPY --chown=5000:5000 --from=builder /go/src/github.com/vulcanize/eth-statediff-service/environments environments
|
||||
RUN apk --no-cache add su-exec bash
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /eth-statediff-service/$CONFIG_FILE config.toml
|
||||
COPY --from=builder /eth-statediff-service/startup_script.sh .
|
||||
|
||||
# keep binaries immutable
|
||||
COPY --from=builder /go/src/github.com/vulcanize/eth-statediff-service/eth-statediff-service eth-statediff-service
|
||||
COPY --from=builder /eth-statediff-service/eth-statediff-service eth-statediff-service
|
||||
|
||||
EXPOSE $EXPOSE_PORT
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
## Build docker image
|
||||
.PHONY: docker-build
|
||||
docker-build:
|
||||
docker build -t vulcanize/eth-statediff-service .
|
||||
@@ -1,68 +1,216 @@
|
||||
# eth-statediff-service
|
||||
|
||||
[](https://goreportcard.com/report/github.com/vulcanize/eth-statediff-service)
|
||||
[](https://goreportcard.com/report/github.com/cerc-io/eth-statediff-service)
|
||||
|
||||
>> standalone statediffing service ontop of leveldb
|
||||
|
||||
Purpose:
|
||||
|
||||
Stand up a statediffing service directly on top of a go-ethereum leveldb instance.
|
||||
A standalone statediffing service which runs directly on top of a `go-ethereum` database instance.
|
||||
This service can serve historical state data over the same rpc interface as
|
||||
[statediffing geth](https://github.com/vulcanize/go-ethereum/releases/tag/v1.9.11-statediff-0.0.5) without needing to run a full node
|
||||
[statediffing geth](https://github.com/cerc-io/go-ethereum) without needing to run a full node.
|
||||
|
||||
## Usage
|
||||
## Setup
|
||||
|
||||
### `serve`
|
||||
Configure access to the private Git server at `git.vdb.to`, then build the executable:
|
||||
|
||||
To serve state diffs over RPC:
|
||||
|
||||
`eth-statediff-service serve --config=<config path>`
|
||||
|
||||
Available RPC methods are:
|
||||
* `statediff_stateTrieAt()`
|
||||
* `statediff_streamCodeAndCodeHash()`
|
||||
* `statediff_stateDiffAt()`
|
||||
* `statediff_writeStateDiffAt()`
|
||||
|
||||
### `write`
|
||||
|
||||
To write state diffs directly to a database:
|
||||
|
||||
`eth-statediff-service write --config=<config path>`
|
||||
|
||||
This depends on the `database` settings being properly configured.
|
||||
```bash
|
||||
go build .
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
An example config file:
|
||||
See [./environments/example.toml](./environments/example.toml) for an annotated example config file.
|
||||
|
||||
```toml
|
||||
[leveldb]
|
||||
path = "/Users/user/Library/Ethereum/geth/chaindata"
|
||||
ancient = "/Users/user/Library/Ethereum/geth/chaindata/ancient"
|
||||
> **Note:** previous versions of this service used different variable names. To update, change the following:
|
||||
> * `LVLDB_*`, `LEVELDB_*` => `ETHDB_*`
|
||||
> * `LOG_FILE_PATH` => `LOG_FILE`
|
||||
|
||||
[server]
|
||||
ipcPath = "~/.vulcanize/vulcanize.ipc"
|
||||
httpPath = "127.0.0.1:8545"
|
||||
### Local Setup
|
||||
|
||||
[write]
|
||||
ranges = [[1, 2], [3, 4]]
|
||||
[write.params]
|
||||
IntermediateStateNodes = true
|
||||
IntermediateStorageNodes = false
|
||||
IncludeBlock = true
|
||||
IncludeReceipts = true
|
||||
IncludeTD = true
|
||||
IncludeCode = false
|
||||
* Create a chain config file `chain.json` according to chain config in genesis json file used by local geth.
|
||||
|
||||
[statediff]
|
||||
workers = 4
|
||||
Example:
|
||||
```json
|
||||
{
|
||||
"chainId": 41337,
|
||||
"homesteadBlock": 0,
|
||||
"eip150Block": 0,
|
||||
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"eip155Block": 0,
|
||||
"eip158Block": 0,
|
||||
"byzantiumBlock": 0,
|
||||
"constantinopleBlock": 0,
|
||||
"petersburgBlock": 0,
|
||||
"istanbulBlock": 0,
|
||||
"clique": {
|
||||
"period": 5,
|
||||
"epoch": 30000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[log]
|
||||
file = "~/.vulcanize/statediff.log"
|
||||
level = "info"
|
||||
Provide the path to the above file in the config.
|
||||
|
||||
[eth]
|
||||
chainID = 1
|
||||
## Usage
|
||||
|
||||
```
|
||||
* Create / update the config file (refer to example config above).
|
||||
|
||||
### `serve`
|
||||
|
||||
* To serve the statediff RPC API:
|
||||
|
||||
```bash
|
||||
./eth-statediff-service serve --config=<config path>
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
./eth-statediff-service serve --config environments/config.toml
|
||||
```
|
||||
|
||||
* Available RPC methods:
|
||||
* `statediff_stateTrieAt()`
|
||||
* `statediff_streamCodeAndCodeHash()`
|
||||
* `statediff_stateDiffAt()`
|
||||
* `statediff_writeStateDiffAt()`
|
||||
* `statediff_writeStateDiffsInRange()`
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
curl -X POST -H 'Content-Type: application/json' --data '{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "statediff_writeStateDiffsInRange",
|
||||
"params": [0, 1, {
|
||||
"ncludeBlock": true,
|
||||
"includeReceipts": true,
|
||||
"includeTD": true,
|
||||
"includeCode": true
|
||||
}
|
||||
],
|
||||
"id": 1
|
||||
}' "$HOST":"$PORT"
|
||||
```
|
||||
|
||||
* Prerun:
|
||||
* The process can be configured locally with sets of ranges to process as a "prerun" to
|
||||
processing directed by the server endpoints.
|
||||
* This is done by turning "prerun" on in the config (`statediff.prerun = true`) and defining
|
||||
ranges and params in the `prerun` section of the config.
|
||||
* Set the range using `prerun.start` and `prerun.stop`. Use `prerun.ranges` if prerun on more
|
||||
than one range is required.
|
||||
|
||||
* NOTE: Currently, `params.includeTD` must be set to / passed as `true`.
|
||||
|
||||
## Monitoring
|
||||
|
||||
* Enable metrics using config parameters `prom.metrics` and `prom.http`.
|
||||
* `eth-statediff-service` exposes following prometheus metrics at `/metrics` endpoint:
|
||||
* `ranges_queued`: Number of range requests currently queued.
|
||||
* `loaded_height`: The last block that was loaded for processing.
|
||||
* `processed_height`: The last block that was processed.
|
||||
* `stats.t_block_load`: Block loading time.
|
||||
* `stats.t_block_processing`: Block (header, uncles, txs, rcts, tx trie, rct trie) processing time.
|
||||
* `stats.t_state_processing`: State (state trie, storage tries, and code) processing time.
|
||||
* `stats.t_postgres_tx_commit`: Postgres tx commit time.
|
||||
* `http.count`: HTTP request count.
|
||||
* `http.duration`: HTTP request duration.
|
||||
* `ipc.count`: Unix socket connection count.
|
||||
|
||||
## Tests
|
||||
|
||||
* Run unit tests:
|
||||
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
## Import output data in file mode into a database
|
||||
|
||||
* When `eth-statediff-service` is run in file mode (`database.type`: `file`) the output is in form of a SQL
|
||||
file or multiple CSV files.
|
||||
|
||||
### SQL
|
||||
|
||||
* Assuming the output files are located in host's `./output_dir` directory.
|
||||
|
||||
* Create a directory to store post-processed output:
|
||||
|
||||
```bash
|
||||
mkdir -p output_dir/processed_output
|
||||
```
|
||||
|
||||
* (Optional) Get row counts in the output:
|
||||
|
||||
```bash
|
||||
wc -l output_dir/statediff.sql > output_stats.txt
|
||||
```
|
||||
|
||||
* De-duplicate data:
|
||||
|
||||
```bash
|
||||
sort -u output_dir/statediff.sql -o output_dir/processed_output/deduped-statediff.sql
|
||||
```
|
||||
|
||||
* Copy over the post-processed output files to the DB server (say in `/output_dir`).
|
||||
|
||||
* Run the following to import data:
|
||||
|
||||
```bash
|
||||
psql -U <DATABASE_USER> -h <DATABASE_HOSTNAME> -p <DATABASE_PORT> <DATABASE_NAME> --set ON_ERROR_STOP=on -f /output_dir/processed_output/deduped-statediff.sql
|
||||
```
|
||||
|
||||
### CSV
|
||||
|
||||
* Create an env file with the required variables. Refer [.sample.env](./scripts/.sample.env).
|
||||
|
||||
* (Optional) Get row counts in the output:
|
||||
|
||||
```bash
|
||||
./scripts/count-lines.sh <ENV_FILE_PATH>
|
||||
```
|
||||
|
||||
* De-duplicate data:
|
||||
|
||||
```bash
|
||||
./scripts/dedup.sh <ENV_FILE_PATH>
|
||||
```
|
||||
|
||||
* Perform column checks:
|
||||
|
||||
```bash
|
||||
./scripts/check-columns.sh <ENV_FILE_PATH>
|
||||
```
|
||||
|
||||
Check the output logs for any rows detected with unexpected number of columns.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
# log
|
||||
eth.header_cids
|
||||
Start: Wednesday 21 September 2022 06:00:38 PM IST
|
||||
Time taken: 00:00:05
|
||||
End: Wednesday 21 September 2022 06:00:43 PM IST
|
||||
Total bad rows: 1 ./check-columns/eth.header_cids.txt
|
||||
|
||||
# bad row output
|
||||
# line number, num. of columns, data
|
||||
23 17 22,xxxxxx,0x07f5ea5c94aa8dea60b28f6b6315d92f2b6d78ca4b74ea409adeb191b5a114f2,0x5918487321aa57dd0c50977856c6231e7c4ee79e95b694c7c8830227d77a1ecc,bagiacgzaa726uxeuvkg6uyfsr5vwgfozf4vw26gkjn2ouqe232yzdnnbctza,45,geth,0,0xad8fa8df61b98dbda7acd6ca76d5ce4cbba663d5f608cc940957adcdb94cee8d,0xc621412320a20b4aaff5363bdf063b9d13e394ef82e55689ab703aae5db08e26,0x71ec1c7d81269ce115be81c81f13e1cc2601c292a7f20440a77257ecfdc69940,0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347,\x2000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000,1658408419,/blocks/DMQAP5PKLSKKVDPKMCZI623DCXMS6K3NPDFEW5HKICNN5MMRWWQRJ4Q,1,0x0000000000000000000000000000000000000000
|
||||
```
|
||||
|
||||
* Import data using `timescaledb-parallel-copy`:
|
||||
(requires [`timescaledb-parallel-copy`](https://github.com/timescale/timescaledb-parallel-copy) installation; readily comes with TimescaleDB docker image)
|
||||
|
||||
```bash
|
||||
./scripts/timescaledb-import.sh <ENV_FILE_PATH>
|
||||
```
|
||||
|
||||
* NOTE: `COPY` command on CSVs inserts empty strings as `NULL` in the DB. Passing `FORCE_NOT_NULL <COLUMN_NAME>` forces it to insert empty strings instead. This is required to maintain compatibility of the imported statediff data with the data generated in `postgres` mode. Reference: https://www.postgresql.org/docs/14/sql-copy.html
|
||||
|
||||
### Stats
|
||||
|
||||
The binary includes a `stats` command which reports stats for the offline DB.
|
||||
|
||||
At this time, the only stat supported is to return the latest/highest block height and hash found in the EthDB. This is
|
||||
useful for determining what the upper limit is for a standalone statediffing process using a given EthDB.
|
||||
|
||||
`./eth-statediff-service stats --config={path to toml config file}`
|
||||
|
||||
+102
-17
@@ -18,8 +18,6 @@ package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
|
||||
pg "github.com/ethereum/go-ethereum/statediff/indexer/postgres"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -28,37 +26,124 @@ const (
|
||||
ETH_GENESIS_BLOCK = "ETH_GENESIS_BLOCK"
|
||||
ETH_NETWORK_ID = "ETH_NETWORK_ID"
|
||||
ETH_CHAIN_ID = "ETH_CHAIN_ID"
|
||||
ETH_CHAIN_CONFIG = "ETH_CHAIN_CONFIG"
|
||||
|
||||
DB_CACHE_SIZE_MB = "DB_CACHE_SIZE_MB"
|
||||
TRIE_CACHE_SIZE_MB = "TRIE_CACHE_SIZE_MB"
|
||||
LVLDB_PATH = "LVLDB_PATH"
|
||||
LVLDB_ANCIENT = "LVLDB_ANCIENT"
|
||||
STATEDIFF_WORKERS = "STATEDIFF_WORKERS"
|
||||
WRITE_SERVER = "WRITE_SERVER"
|
||||
// ETHDB_ENGINE = "ETHDB_ENGINE"
|
||||
ETHDB_PATH = "ETHDB_PATH"
|
||||
ETHDB_ANCIENT = "ETHDB_ANCIENT"
|
||||
|
||||
STATEDIFF_PRERUN = "STATEDIFF_PRERUN"
|
||||
STATEDIFF_TRIE_WORKERS = "STATEDIFF_TRIE_WORKERS"
|
||||
STATEDIFF_SERVICE_WORKERS = "STATEDIFF_SERVICE_WORKERS"
|
||||
STATEDIFF_WORKER_QUEUE_SIZE = "STATEDIFF_WORKER_QUEUE_SIZE"
|
||||
|
||||
SERVICE_IPC_PATH = "SERVICE_IPC_PATH"
|
||||
SERVICE_HTTP_PATH = "SERVICE_HTTP_PATH"
|
||||
|
||||
PROM_METRICS = "PROM_METRICS"
|
||||
PROM_HTTP = "PROM_HTTP"
|
||||
PROM_HTTP_ADDR = "PROM_HTTP_ADDR"
|
||||
PROM_HTTP_PORT = "PROM_HTTP_PORT"
|
||||
PROM_DB_STATS = "PROM_DB_STATS"
|
||||
|
||||
PRERUN_ONLY = "PRERUN_ONLY"
|
||||
PRERUN_PARALLEL = "PRERUN_PARALLEL"
|
||||
PRERUN_RANGE_START = "PRERUN_RANGE_START"
|
||||
PRERUN_RANGE_STOP = "PRERUN_RANGE_STOP"
|
||||
PRERUN_INCLUDE_BLOCK = "PRERUN_INCLUDE_BLOCK"
|
||||
PRERUN_INCLUDE_RECEIPTS = "PRERUN_INCLUDE_RECEIPTS"
|
||||
PRERUN_INCLUDE_TD = "PRERUN_INCLUDE_TD"
|
||||
PRERUN_INCLUDE_CODE = "PRERUN_INCLUDE_CODE"
|
||||
|
||||
LOG_LEVEL = "LOG_LEVEL"
|
||||
LOG_FILE = "LOG_FILE"
|
||||
|
||||
DATABASE_NAME = "DATABASE_NAME"
|
||||
DATABASE_HOSTNAME = "DATABASE_HOSTNAME"
|
||||
DATABASE_PORT = "DATABASE_PORT"
|
||||
DATABASE_USER = "DATABASE_USER"
|
||||
DATABASE_PASSWORD = "DATABASE_PASSWORD"
|
||||
|
||||
DATABASE_TYPE = "DATABASE_TYPE"
|
||||
DATABASE_DRIVER_TYPE = "DATABASE_DRIVER_TYPE"
|
||||
DATABASE_DUMP_DST = "DATABASE_DUMP_DST"
|
||||
DATABASE_FILE_PATH = "DATABASE_FILE_PATH"
|
||||
DATABASE_FILE_MODE = "DATABASE_FILE_MODE"
|
||||
DATABASE_FILE_CSV_DIR = "DATABASE_FILE_CSV_DIR"
|
||||
|
||||
DATABASE_MAX_IDLE_CONNECTIONS = "DATABASE_MAX_IDLE_CONNECTIONS"
|
||||
DATABASE_MAX_OPEN_CONNECTIONS = "DATABASE_MAX_OPEN_CONNECTIONS"
|
||||
DATABASE_MIN_OPEN_CONNS = "DATABASE_MIN_OPEN_CONNS"
|
||||
DATABASE_MAX_CONN_LIFETIME = "DATABASE_MAX_CONN_LIFETIME"
|
||||
DATABASE_CONN_TIMEOUT = "DATABSE_CONN_TIMEOUT"
|
||||
DATABASE_MAX_CONN_IDLE_TIME = "DATABASE_MAX_CONN_IDLE_TIME"
|
||||
|
||||
DEBUG_PPROF = "DEBUG_PPROF"
|
||||
)
|
||||
|
||||
// Bind env vars for eth node and DB configuration
|
||||
func init() {
|
||||
viper.BindEnv("server.ipcPath", SERVICE_IPC_PATH)
|
||||
viper.BindEnv("server.httpPath", SERVICE_HTTP_PATH)
|
||||
|
||||
viper.BindEnv("ethereum.nodeID", ETH_NODE_ID)
|
||||
viper.BindEnv("ethereum.clientName", ETH_CLIENT_NAME)
|
||||
viper.BindEnv("ethereum.genesisBlock", ETH_GENESIS_BLOCK)
|
||||
viper.BindEnv("ethereum.networkID", ETH_NETWORK_ID)
|
||||
viper.BindEnv("ethereum.chainID", ETH_CHAIN_ID)
|
||||
viper.BindEnv("ethereum.chainConfig", ETH_CHAIN_CONFIG)
|
||||
|
||||
viper.BindEnv("database.name", pg.DATABASE_NAME)
|
||||
viper.BindEnv("database.hostname", pg.DATABASE_HOSTNAME)
|
||||
viper.BindEnv("database.port", pg.DATABASE_PORT)
|
||||
viper.BindEnv("database.user", pg.DATABASE_USER)
|
||||
viper.BindEnv("database.password", pg.DATABASE_PASSWORD)
|
||||
viper.BindEnv("database.maxIdle", pg.DATABASE_MAX_IDLE_CONNECTIONS)
|
||||
viper.BindEnv("database.maxOpen", pg.DATABASE_MAX_OPEN_CONNECTIONS)
|
||||
viper.BindEnv("database.maxLifetime", pg.DATABASE_MAX_CONN_LIFETIME)
|
||||
viper.BindEnv("database.name", DATABASE_NAME)
|
||||
viper.BindEnv("database.hostname", DATABASE_HOSTNAME)
|
||||
viper.BindEnv("database.port", DATABASE_PORT)
|
||||
viper.BindEnv("database.user", DATABASE_USER)
|
||||
viper.BindEnv("database.password", DATABASE_PASSWORD)
|
||||
|
||||
viper.BindEnv("database.maxIdle", DATABASE_MAX_IDLE_CONNECTIONS)
|
||||
viper.BindEnv("database.maxOpen", DATABASE_MAX_OPEN_CONNECTIONS)
|
||||
viper.BindEnv("database.minOpen", DATABASE_MIN_OPEN_CONNS)
|
||||
viper.BindEnv("database.maxConnLifetime", DATABASE_MAX_CONN_LIFETIME)
|
||||
viper.BindEnv("database.connTimeout", DATABASE_CONN_TIMEOUT)
|
||||
viper.BindEnv("database.maxIdleTime", DATABASE_MAX_CONN_IDLE_TIME)
|
||||
|
||||
viper.BindEnv("database.type", DATABASE_TYPE)
|
||||
viper.BindEnv("database.driver", DATABASE_DRIVER_TYPE)
|
||||
viper.BindEnv("database.dumpDestination", DATABASE_DUMP_DST)
|
||||
viper.BindEnv("database.fileMode", DATABASE_FILE_MODE)
|
||||
viper.BindEnv("database.filePath", DATABASE_FILE_PATH)
|
||||
viper.BindEnv("database.fileCsvDir", DATABASE_FILE_CSV_DIR)
|
||||
|
||||
viper.BindEnv("cache.database", DB_CACHE_SIZE_MB)
|
||||
viper.BindEnv("cache.trie", TRIE_CACHE_SIZE_MB)
|
||||
|
||||
viper.BindEnv("leveldb.path", LVLDB_PATH)
|
||||
viper.BindEnv("leveldb.ancient", LVLDB_ANCIENT)
|
||||
// viper.BindEnv("ethdb.engine", ETHDB_ENGINE)
|
||||
viper.BindEnv("ethdb.path", ETHDB_PATH)
|
||||
viper.BindEnv("ethdb.ancient", ETHDB_ANCIENT)
|
||||
|
||||
viper.BindEnv("statediff.workers", STATEDIFF_WORKERS)
|
||||
viper.BindEnv("prom.metrics", PROM_METRICS)
|
||||
viper.BindEnv("prom.http", PROM_HTTP)
|
||||
viper.BindEnv("prom.httpAddr", PROM_HTTP_ADDR)
|
||||
viper.BindEnv("prom.httpPort", PROM_HTTP_PORT)
|
||||
viper.BindEnv("prom.dbStats", PROM_DB_STATS)
|
||||
|
||||
viper.BindEnv("statediff.serviceWorkers", STATEDIFF_SERVICE_WORKERS)
|
||||
viper.BindEnv("statediff.trieWorkers", STATEDIFF_TRIE_WORKERS)
|
||||
viper.BindEnv("statediff.workerQueueSize", STATEDIFF_WORKER_QUEUE_SIZE)
|
||||
|
||||
viper.BindEnv("statediff.prerun", STATEDIFF_PRERUN)
|
||||
viper.BindEnv("prerun.only", PRERUN_ONLY)
|
||||
viper.BindEnv("prerun.parallel", PRERUN_PARALLEL)
|
||||
viper.BindEnv("prerun.start", PRERUN_RANGE_START)
|
||||
viper.BindEnv("prerun.stop", PRERUN_RANGE_STOP)
|
||||
viper.BindEnv("prerun.params.includeBlock", PRERUN_INCLUDE_BLOCK)
|
||||
viper.BindEnv("prerun.params.includeReceipts", PRERUN_INCLUDE_RECEIPTS)
|
||||
viper.BindEnv("prerun.params.includeTD", PRERUN_INCLUDE_TD)
|
||||
viper.BindEnv("prerun.params.includeCode", PRERUN_INCLUDE_CODE)
|
||||
|
||||
viper.BindEnv("log.level", LOG_LEVEL)
|
||||
viper.BindEnv("log.file", LOG_FILE)
|
||||
|
||||
viper.BindEnv("debug.pprof", DEBUG_PPROF)
|
||||
}
|
||||
|
||||
+243
-30
@@ -18,14 +18,23 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/statediff/indexer/node"
|
||||
"github.com/ethereum/go-ethereum/statediff/indexer/postgres"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/database/dump"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/database/file"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/database/sql/postgres"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/interfaces"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/node"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/shared"
|
||||
"github.com/ethereum/go-ethereum/cmd/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/cerc-io/eth-statediff-service/pkg/prom"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -40,7 +49,6 @@ var rootCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
log.Info("----- Starting vDB -----")
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -64,10 +72,24 @@ func initFuncs(cmd *cobra.Command, args []string) {
|
||||
if err := logLevel(); err != nil {
|
||||
log.Fatal("Could not set log level: ", err)
|
||||
}
|
||||
|
||||
if viper.GetBool("prom.metrics") {
|
||||
log.Info("initializing prometheus metrics")
|
||||
prom.Init()
|
||||
}
|
||||
|
||||
if viper.GetBool("prom.http") {
|
||||
addr := fmt.Sprintf(
|
||||
"%s:%s",
|
||||
viper.GetString("prom.httpAddr"),
|
||||
viper.GetString("prom.httpPort"),
|
||||
)
|
||||
log.Info("starting prometheus server")
|
||||
prom.Listen(addr)
|
||||
}
|
||||
}
|
||||
|
||||
func logLevel() error {
|
||||
viper.BindEnv("log.level", "LOGRUS_LEVEL")
|
||||
lvl, err := log.ParseLevel(viper.GetString("log.level"))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -85,54 +107,134 @@ func init() {
|
||||
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
viper.AutomaticEnv()
|
||||
|
||||
rootCmd.PersistentFlags().String("http-path", "", "vdb server http path")
|
||||
rootCmd.PersistentFlags().String("ipc-path", "", "vdb server ipc path")
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file location")
|
||||
|
||||
rootCmd.PersistentFlags().String("log-file", "", "file path for logging")
|
||||
rootCmd.PersistentFlags().String("log-level", log.InfoLevel.String(),
|
||||
"log level (trace, debug, info, warn, error, fatal, panic")
|
||||
|
||||
rootCmd.PersistentFlags().String("leveldb-path", "", "path to primary datastore")
|
||||
// rootCmd.PersistentFlags().String("ethdb-engine", "local", "Ethdb engine type (leveldb, pebble)")
|
||||
rootCmd.PersistentFlags().String("ethdb-path", "", "path to primary datastore")
|
||||
rootCmd.PersistentFlags().String("ancient-path", "", "path to ancient datastore")
|
||||
rootCmd.PersistentFlags().Int("workers", 0, "number of concurrent workers to use")
|
||||
|
||||
rootCmd.PersistentFlags().String("database-name", "vulcanize_public", "database name")
|
||||
rootCmd.PersistentFlags().Bool("prerun", false, "turn on prerun of toml configured ranges")
|
||||
rootCmd.PersistentFlags().Int("service-workers", 1, "number of range requests to process concurrently")
|
||||
rootCmd.PersistentFlags().Int("trie-workers", 1, "number of workers to use for trie traversal and processing")
|
||||
rootCmd.PersistentFlags().Int("worker-queue-size", 1024, "size of the range request queue for service workers")
|
||||
|
||||
rootCmd.PersistentFlags().String("database-name", "cerc_public", "database name")
|
||||
rootCmd.PersistentFlags().Int("database-port", 5432, "database port")
|
||||
rootCmd.PersistentFlags().String("database-hostname", "localhost", "database hostname")
|
||||
rootCmd.PersistentFlags().String("database-user", "", "database user")
|
||||
rootCmd.PersistentFlags().String("database-password", "", "database password")
|
||||
rootCmd.PersistentFlags().Int("database-max-idle", 0, "database max number of idle connections")
|
||||
rootCmd.PersistentFlags().Int("database-max-open", 0, "database max number of open connections")
|
||||
rootCmd.PersistentFlags().Int("database-min-open", 0, "database min number of open connections")
|
||||
rootCmd.PersistentFlags().Duration("database-max-conn-lifetime", 0, "database max connection lifetime")
|
||||
rootCmd.PersistentFlags().Duration("database-conn-timeout", 0, "database connection timeout")
|
||||
rootCmd.PersistentFlags().Duration("database-max-idle-time", 0, "database max connection idle time")
|
||||
rootCmd.PersistentFlags().String("database-type", "postgres", "database type (currently supported: postgres, dump)")
|
||||
rootCmd.PersistentFlags().String("database-driver", "sqlx", "database driver type (currently supported: sqlx, pgx)")
|
||||
rootCmd.PersistentFlags().String("database-dump-dst", "stdout", "dump destination (for database-type=dump; options: stdout, stderr, discard)")
|
||||
rootCmd.PersistentFlags().String("database-file-mode", "csv", "mode for writing file (for database-type=file; options: csv, sql)")
|
||||
rootCmd.PersistentFlags().String("database-file-csv-dir", "", "full directory path (for database-file-mode=csv)")
|
||||
rootCmd.PersistentFlags().String("database-file-path", "", "full file path (for database-file-mode=sql)")
|
||||
|
||||
rootCmd.PersistentFlags().String("eth-node-id", "", "eth node id")
|
||||
rootCmd.PersistentFlags().String("eth-client-name", "Geth", "eth client name")
|
||||
rootCmd.PersistentFlags().String("eth-client-name", "eth-statediff-service", "eth client name")
|
||||
rootCmd.PersistentFlags().String("eth-genesis-block",
|
||||
"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", "eth genesis block hash")
|
||||
rootCmd.PersistentFlags().String("eth-network-id", "1", "eth network id")
|
||||
rootCmd.PersistentFlags().String("eth-chain-id", "1", "eth chain id")
|
||||
|
||||
rootCmd.PersistentFlags().Int("cache-db", 1024, "megabytes of memory allocated to database cache")
|
||||
rootCmd.PersistentFlags().Int("cache-trie", 1024, "Megabytes of memory allocated to trie cache")
|
||||
|
||||
rootCmd.PersistentFlags().Bool("prom-http", false, "enable prometheus http service")
|
||||
rootCmd.PersistentFlags().String("prom-http-addr", "127.0.0.1", "prometheus http host")
|
||||
rootCmd.PersistentFlags().String("prom-http-port", "8080", "prometheus http port")
|
||||
rootCmd.PersistentFlags().Bool("prom-db-stats", false, "enables prometheus db stats")
|
||||
rootCmd.PersistentFlags().Bool("prom-metrics", false, "enable prometheus metrics")
|
||||
|
||||
rootCmd.PersistentFlags().Bool("prerun-only", false, "only process pre-configured ranges; exit afterwards")
|
||||
rootCmd.PersistentFlags().Int("prerun-start", 0, "start height for a prerun range")
|
||||
rootCmd.PersistentFlags().Int("prerun-stop", 0, "stop height for a prerun range")
|
||||
rootCmd.PersistentFlags().Bool("prerun-include-block", true, "include block data in the statediff payload")
|
||||
rootCmd.PersistentFlags().Bool("prerun-include-receipts", true, "include receipts in the statediff payload")
|
||||
rootCmd.PersistentFlags().Bool("prerun-include-td", true, "include td in the statediff payload")
|
||||
rootCmd.PersistentFlags().Bool("prerun-include-code", true, "include code and codehash mappings in statediff payload")
|
||||
|
||||
viper.BindPFlag("server.httpPath", rootCmd.PersistentFlags().Lookup("http-path"))
|
||||
viper.BindPFlag("server.ipcPath", rootCmd.PersistentFlags().Lookup("ipc-path"))
|
||||
|
||||
viper.BindPFlag("log.file", rootCmd.PersistentFlags().Lookup("log-file"))
|
||||
viper.BindPFlag("log.level", rootCmd.PersistentFlags().Lookup("log-level"))
|
||||
viper.BindPFlag("statediff.workers", rootCmd.PersistentFlags().Lookup("workers"))
|
||||
viper.BindPFlag("leveldb.path", rootCmd.PersistentFlags().Lookup("leveldb-path"))
|
||||
viper.BindPFlag("leveldb.ancient", rootCmd.PersistentFlags().Lookup("ancient-path"))
|
||||
|
||||
viper.BindPFlag("statediff.prerun", rootCmd.PersistentFlags().Lookup("prerun"))
|
||||
viper.BindPFlag("statediff.serviceWorkers", rootCmd.PersistentFlags().Lookup("service-workers"))
|
||||
viper.BindPFlag("statediff.trieWorkers", rootCmd.PersistentFlags().Lookup("trie-workers"))
|
||||
viper.BindPFlag("statediff.workerQueueSize", rootCmd.PersistentFlags().Lookup("worker-queue-size"))
|
||||
|
||||
// viper.BindPFlag("ethdb.engine", rootCmd.PersistentFlags().Lookup("ethdb-engine"))
|
||||
viper.BindPFlag("ethdb.path", rootCmd.PersistentFlags().Lookup("ethdb-path"))
|
||||
viper.BindPFlag("ethdb.ancient", rootCmd.PersistentFlags().Lookup("ancient-path"))
|
||||
viper.BindPFlag("ethdb.url", rootCmd.PersistentFlags().Lookup("ethdb-url"))
|
||||
|
||||
viper.BindPFlag("database.name", rootCmd.PersistentFlags().Lookup("database-name"))
|
||||
viper.BindPFlag("database.port", rootCmd.PersistentFlags().Lookup("database-port"))
|
||||
viper.BindPFlag("database.hostname", rootCmd.PersistentFlags().Lookup("database-hostname"))
|
||||
viper.BindPFlag("database.user", rootCmd.PersistentFlags().Lookup("database-user"))
|
||||
viper.BindPFlag("database.password", rootCmd.PersistentFlags().Lookup("database-password"))
|
||||
viper.BindPFlag("database.maxIdle", rootCmd.PersistentFlags().Lookup("database-max-idle"))
|
||||
viper.BindPFlag("database.maxOpen", rootCmd.PersistentFlags().Lookup("database-max-open"))
|
||||
viper.BindPFlag("database.minOpen", rootCmd.PersistentFlags().Lookup("database-min-open"))
|
||||
viper.BindPFlag("database.maxConnLifetime", rootCmd.PersistentFlags().Lookup("database-max-conn-lifetime"))
|
||||
viper.BindPFlag("database.connTimeout", rootCmd.PersistentFlags().Lookup("database-conn-timeout"))
|
||||
viper.BindPFlag("database.maxIdleTime", rootCmd.PersistentFlags().Lookup("database-max-idle-time"))
|
||||
viper.BindPFlag("database.type", rootCmd.PersistentFlags().Lookup("database-type"))
|
||||
viper.BindPFlag("database.driver", rootCmd.PersistentFlags().Lookup("database-driver"))
|
||||
viper.BindPFlag("database.dumpDestination", rootCmd.PersistentFlags().Lookup("database-dump-dst"))
|
||||
viper.BindPFlag("database.fileMode", rootCmd.PersistentFlags().Lookup("database-file-mode"))
|
||||
viper.BindPFlag("database.fileCsvDir", rootCmd.PersistentFlags().Lookup("database-file-csv-dir"))
|
||||
viper.BindPFlag("database.filePath", rootCmd.PersistentFlags().Lookup("database-file-path"))
|
||||
|
||||
viper.BindPFlag("ethereum.nodeID", rootCmd.PersistentFlags().Lookup("eth-node-id"))
|
||||
viper.BindPFlag("ethereum.clientName", rootCmd.PersistentFlags().Lookup("eth-client-name"))
|
||||
viper.BindPFlag("ethereum.genesisBlock", rootCmd.PersistentFlags().Lookup("eth-genesis-block"))
|
||||
viper.BindPFlag("ethereum.networkID", rootCmd.PersistentFlags().Lookup("eth-network-id"))
|
||||
viper.BindPFlag("ethereum.chainID", rootCmd.PersistentFlags().Lookup("eth-chain-id"))
|
||||
viper.BindPFlag("ethereum.chainConfig", rootCmd.PersistentFlags().Lookup("eth-chain-config"))
|
||||
|
||||
viper.BindPFlag("cache.database", rootCmd.PersistentFlags().Lookup("cache-db"))
|
||||
viper.BindPFlag("cache.trie", rootCmd.PersistentFlags().Lookup("cache-trie"))
|
||||
|
||||
viper.BindPFlag("prom.http", rootCmd.PersistentFlags().Lookup("prom-http"))
|
||||
viper.BindPFlag("prom.httpAddr", rootCmd.PersistentFlags().Lookup("prom-http-addr"))
|
||||
viper.BindPFlag("prom.httpPort", rootCmd.PersistentFlags().Lookup("prom-http-port"))
|
||||
viper.BindPFlag("prom.dbStats", rootCmd.PersistentFlags().Lookup("prom-db-stats"))
|
||||
viper.BindPFlag("prom.metrics", rootCmd.PersistentFlags().Lookup("prom-metrics"))
|
||||
|
||||
viper.BindPFlag("prerun.only", rootCmd.PersistentFlags().Lookup("prerun-only"))
|
||||
viper.BindPFlag("prerun.parallel", rootCmd.PersistentFlags().Lookup("prerun-parallel"))
|
||||
viper.BindPFlag("prerun.start", rootCmd.PersistentFlags().Lookup("prerun-start"))
|
||||
viper.BindPFlag("prerun.stop", rootCmd.PersistentFlags().Lookup("prerun-stop"))
|
||||
viper.BindPFlag("prerun.params.includeBlock", rootCmd.PersistentFlags().Lookup("prerun-include-block"))
|
||||
viper.BindPFlag("prerun.params.includeReceipts", rootCmd.PersistentFlags().Lookup("prerun-include-receipts"))
|
||||
viper.BindPFlag("prerun.params.includeTD", rootCmd.PersistentFlags().Lookup("prerun-include-td"))
|
||||
viper.BindPFlag("prerun.params.includeCode", rootCmd.PersistentFlags().Lookup("prerun-include-code"))
|
||||
|
||||
viper.BindPFlag("debug.pprof", rootCmd.PersistentFlags().Lookup("debug-pprof"))
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
viper.SetConfigFile(cfgFile)
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
log.Printf("Using config file: %s", viper.ConfigFileUsed())
|
||||
log.Infof("Using config file: %s", viper.ConfigFileUsed())
|
||||
} else {
|
||||
log.Fatal(fmt.Sprintf("Couldn't read config file: %s", err.Error()))
|
||||
}
|
||||
@@ -141,30 +243,141 @@ func initConfig() {
|
||||
}
|
||||
}
|
||||
|
||||
func GetEthNodeInfo() node.Info {
|
||||
func getEthNodeInfo() node.Info {
|
||||
var nodeID, genesisBlock, networkID, clientName string
|
||||
var chainID uint64
|
||||
if !viper.IsSet("ethereum.nodeID") {
|
||||
nodeID = randSeq(12)
|
||||
} else {
|
||||
nodeID = viper.GetString("ethereum.nodeID")
|
||||
}
|
||||
genesisBlock = viper.GetString("ethereum.genesisBlock")
|
||||
if !viper.IsSet("ethereum.genesisBlock") {
|
||||
genesisBlock = "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"
|
||||
} else {
|
||||
genesisBlock = viper.GetString("ethereum.genesisBlock")
|
||||
}
|
||||
if !viper.IsSet("ethereum.chainID") {
|
||||
chainID = 1
|
||||
} else {
|
||||
chainID = viper.GetUint64("ethereum.chainID")
|
||||
}
|
||||
if !viper.IsSet("ethereum.networkID") {
|
||||
networkID = "1"
|
||||
} else {
|
||||
networkID = viper.GetString("ethereum.networkID")
|
||||
}
|
||||
if !viper.IsSet("ethereum.clientName") {
|
||||
clientName = "eth-statediff-service"
|
||||
} else {
|
||||
clientName = viper.GetString("ethereum.clientName")
|
||||
}
|
||||
return node.Info{
|
||||
ID: viper.GetString("ethereum.nodeID"),
|
||||
ClientName: viper.GetString("ethereum.clientName"),
|
||||
GenesisBlock: viper.GetString("ethereum.genesisBlock"),
|
||||
NetworkID: viper.GetString("ethereum.networkID"),
|
||||
ChainID: viper.GetUint64("ethereum.chainID"),
|
||||
ID: nodeID,
|
||||
ClientName: clientName,
|
||||
GenesisBlock: genesisBlock,
|
||||
NetworkID: networkID,
|
||||
ChainID: chainID,
|
||||
}
|
||||
}
|
||||
|
||||
func GetDBParams() postgres.ConnectionParams {
|
||||
return postgres.ConnectionParams{
|
||||
Name: viper.GetString("database.name"),
|
||||
Hostname: viper.GetString("database.hostname"),
|
||||
Port: viper.GetInt("database.port"),
|
||||
User: viper.GetString("database.user"),
|
||||
Password: viper.GetString("database.password"),
|
||||
var characters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
||||
|
||||
func randSeq(n int) string {
|
||||
b := make([]rune, n)
|
||||
for i := range b {
|
||||
b[i] = characters[rand.Intn(len(characters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func GetDBConfig() postgres.ConnectionConfig {
|
||||
return postgres.ConnectionConfig{
|
||||
MaxIdle: viper.GetInt("database.maxIdle"),
|
||||
MaxOpen: viper.GetInt("database.maxOpen"),
|
||||
MaxLifetime: viper.GetInt("database.maxLifetime"),
|
||||
// getConfig constructs and returns the appropriate config from viper params
|
||||
func getConfig(nodeInfo node.Info) (interfaces.Config, error) {
|
||||
dbTypeStr := viper.GetString("database.type")
|
||||
dbType, err := shared.ResolveDBType(dbTypeStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logWithCommand.Debugf("Configuring service for database type: %s", dbType)
|
||||
var indexerConfig interfaces.Config
|
||||
switch dbType {
|
||||
case shared.FILE:
|
||||
logWithCommand.Info("Starting in sql file writing mode")
|
||||
|
||||
fileModeStr := viper.GetString("database.fileMode")
|
||||
fileMode, err := file.ResolveFileMode(fileModeStr)
|
||||
if err != nil {
|
||||
utils.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
filePathStr := viper.GetString("database.filePath")
|
||||
if fileMode == file.SQL && filePathStr == "" {
|
||||
logWithCommand.Fatal("When operating in sql file writing mode a file path must be provided")
|
||||
}
|
||||
|
||||
fileCsvDirStr := viper.GetString("database.fileCsvDir")
|
||||
if fileMode == file.CSV && fileCsvDirStr == "" {
|
||||
logWithCommand.Fatal("When operating in csv file writing mode a directory path must be provided")
|
||||
}
|
||||
|
||||
indexerConfig = file.Config{
|
||||
Mode: fileMode,
|
||||
OutputDir: fileCsvDirStr,
|
||||
FilePath: filePathStr,
|
||||
}
|
||||
case shared.DUMP:
|
||||
logWithCommand.Info("Starting in data dump mode")
|
||||
dumpDstStr := viper.GetString("database.dumpDestination")
|
||||
dumpDst, err := dump.ResolveDumpType(dumpDstStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch dumpDst {
|
||||
case dump.STDERR:
|
||||
indexerConfig = dump.Config{Dump: os.Stdout}
|
||||
case dump.STDOUT:
|
||||
indexerConfig = dump.Config{Dump: os.Stderr}
|
||||
case dump.DISCARD:
|
||||
indexerConfig = dump.Config{Dump: dump.Discard}
|
||||
default:
|
||||
return nil, fmt.Errorf("unrecognized dump destination: %s", dumpDst)
|
||||
}
|
||||
case shared.POSTGRES:
|
||||
logWithCommand.Info("Starting in postgres mode")
|
||||
driverTypeStr := viper.GetString("database.driver")
|
||||
driverType, err := postgres.ResolveDriverType(driverTypeStr)
|
||||
if err != nil {
|
||||
utils.Fatalf("%v", err)
|
||||
}
|
||||
pgConfig := postgres.Config{
|
||||
Hostname: viper.GetString("database.hostname"),
|
||||
Port: viper.GetInt("database.port"),
|
||||
DatabaseName: viper.GetString("database.name"),
|
||||
Username: viper.GetString("database.user"),
|
||||
Password: viper.GetString("database.password"),
|
||||
Driver: driverType,
|
||||
}
|
||||
if viper.IsSet("database.maxIdle") {
|
||||
pgConfig.MaxIdle = viper.GetInt("database.maxIdle")
|
||||
}
|
||||
if viper.IsSet("database.maxOpen") {
|
||||
pgConfig.MaxConns = viper.GetInt("database.maxOpen")
|
||||
}
|
||||
if viper.IsSet("database.minOpen") {
|
||||
pgConfig.MinConns = viper.GetInt("database.minOpen")
|
||||
}
|
||||
if viper.IsSet("database.maxConnLifetime") {
|
||||
pgConfig.MaxConnLifetime = viper.GetDuration("database.maxConnLifetime")
|
||||
}
|
||||
if viper.IsSet("database.connTimeout") {
|
||||
pgConfig.ConnTimeout = viper.GetDuration("database.connTimeout")
|
||||
}
|
||||
if viper.IsSet("database.maxIdleTime") {
|
||||
pgConfig.MaxConnIdleTime = viper.GetDuration("database.maxIdleTime")
|
||||
}
|
||||
indexerConfig = pgConfig
|
||||
default:
|
||||
return nil, fmt.Errorf("unrecognized db type: %s", dbType)
|
||||
}
|
||||
return indexerConfig, nil
|
||||
}
|
||||
|
||||
+57
-91
@@ -16,30 +16,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum/node"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
ind "github.com/ethereum/go-ethereum/statediff/indexer"
|
||||
"github.com/ethereum/go-ethereum/statediff/indexer/postgres"
|
||||
|
||||
sd "github.com/vulcanize/eth-statediff-service/pkg"
|
||||
pkg "github.com/cerc-io/eth-statediff-service/pkg"
|
||||
srpc "github.com/cerc-io/eth-statediff-service/pkg/rpc"
|
||||
)
|
||||
|
||||
// serveCmd represents the serve command
|
||||
var serveCmd = &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "Standup a standalone statediffing RPC service on top of leveldb",
|
||||
Long: `Usage
|
||||
Short: "Standalone statediffing RPC service on top of an Ethereum database",
|
||||
Long: `Usage:
|
||||
|
||||
./eth-statediff-service serve --config={path to toml config file}`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
@@ -49,122 +46,91 @@ var serveCmd = &cobra.Command{
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(serveCmd)
|
||||
}
|
||||
|
||||
func maxParallelism() int {
|
||||
maxProcs := runtime.GOMAXPROCS(0)
|
||||
numCPU := runtime.NumCPU()
|
||||
if maxProcs < numCPU {
|
||||
return maxProcs
|
||||
}
|
||||
return numCPU
|
||||
}
|
||||
|
||||
func serve() {
|
||||
logWithCommand.Info("starting statediff RPC service")
|
||||
logWithCommand.Debug("Running eth-statediff-service serve command")
|
||||
logWithCommand.Debugf("Parallelism: %d", maxParallelism())
|
||||
|
||||
// load params
|
||||
path := viper.GetString("leveldb.path")
|
||||
ancientPath := viper.GetString("leveldb.ancient")
|
||||
if path == "" || ancientPath == "" {
|
||||
logWithCommand.Fatal("require a valid eth leveldb primary datastore path and ancient datastore path")
|
||||
}
|
||||
reader, chainConf, nodeInfo := createReader()
|
||||
|
||||
nodeInfo := GetEthNodeInfo()
|
||||
config, err := chainConfig(nodeInfo.ChainID)
|
||||
reportLatestBlock(reader)
|
||||
|
||||
service, err := createStateDiffService(reader, chainConf, nodeInfo)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
// create leveldb reader
|
||||
logWithCommand.Info("Creating leveldb reader")
|
||||
conf := sd.ReaderConfig{
|
||||
TrieConfig: &trie.Config{
|
||||
Cache: viper.GetInt("cache.trie"),
|
||||
Journal: "",
|
||||
Preimages: false,
|
||||
},
|
||||
ChainConfig: config,
|
||||
Path: path,
|
||||
AncientPath: ancientPath,
|
||||
DBCacheSize: viper.GetInt("cache.database"),
|
||||
}
|
||||
lvlDBReader, err := sd.NewLvlDBReader(conf)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
// Enable the pprof agent if configured
|
||||
if viper.GetBool("debug.pprof") {
|
||||
// See: https://www.farsightsecurity.com/blog/txt-record/go-remote-profiling-20161028/
|
||||
// For security reasons: do not use the default http multiplexor elsewhere in this process.
|
||||
go func() {
|
||||
logWithCommand.Info("Starting pprof listener on port 6060")
|
||||
logWithCommand.Fatal(http.ListenAndServe("localhost:6060", nil))
|
||||
}()
|
||||
}
|
||||
|
||||
// create statediff service
|
||||
logWithCommand.Info("Creating statediff service")
|
||||
db, err := postgres.NewDB(postgres.DbConnectionString(GetDBParams()), GetDBConfig(), nodeInfo)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
indexer, err := ind.NewStateDiffIndexer(config, db)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
statediffService, err := sd.NewStateDiffService(lvlDBReader, indexer, viper.GetUint("statediff.workers"))
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
// short circuit if we only want to perform prerun
|
||||
if viper.GetBool("prerun.only") {
|
||||
parallel := viper.GetBool("prerun.parallel")
|
||||
if err := service.Run(nil, parallel); err != nil {
|
||||
logWithCommand.Fatalf("Unable to perform prerun: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// start service and servers
|
||||
logWithCommand.Info("Starting statediff service")
|
||||
wg := new(sync.WaitGroup)
|
||||
go statediffService.Loop(wg)
|
||||
logWithCommand.Info("Starting RPC servers")
|
||||
if err := startServers(statediffService); err != nil {
|
||||
var wg sync.WaitGroup
|
||||
if err := service.Loop(&wg); err != nil {
|
||||
logWithCommand.Fatalf("unable to start statediff service: %v", err)
|
||||
}
|
||||
|
||||
if err := startServers(service); err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
logWithCommand.Info("RPC servers successfully spun up; awaiting requests")
|
||||
logWithCommand.Debug("RPC servers successfully spun up; awaiting requests")
|
||||
|
||||
// clean shutdown
|
||||
shutdown := make(chan os.Signal)
|
||||
signal.Notify(shutdown, os.Interrupt)
|
||||
<-shutdown
|
||||
logWithCommand.Info("Received interrupt signal, shutting down")
|
||||
statediffService.Stop()
|
||||
service.Stop()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(serveCmd)
|
||||
|
||||
serveCmd.PersistentFlags().String("http-path", "", "vdb server http path")
|
||||
serveCmd.PersistentFlags().String("ipc-path", "", "vdb server ipc path")
|
||||
|
||||
viper.BindPFlag("server.httpPath", serveCmd.PersistentFlags().Lookup("http-path"))
|
||||
viper.BindPFlag("server.ipcPath", serveCmd.PersistentFlags().Lookup("ipc-path"))
|
||||
}
|
||||
|
||||
func startServers(serv sd.IService) error {
|
||||
viper.BindEnv("server.ipcPath", "SERVER_IPC_PATH")
|
||||
viper.BindEnv("server.httpPath", "SERVER_HTTP_PATH")
|
||||
func startServers(serv *pkg.Service) error {
|
||||
ipcPath := viper.GetString("server.ipcPath")
|
||||
httpPath := viper.GetString("server.httpPath")
|
||||
if ipcPath == "" && httpPath == "" {
|
||||
logWithCommand.Fatal("need an ipc path and/or an http path")
|
||||
logWithCommand.Fatal("Need an IPC path and/or an HTTP path")
|
||||
}
|
||||
if ipcPath != "" {
|
||||
logWithCommand.Info("starting up IPC server")
|
||||
_, _, err := rpc.StartIPCEndpoint(ipcPath, serv.APIs())
|
||||
_, _, err := srpc.StartIPCEndpoint(ipcPath, serv.APIs())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if httpPath != "" {
|
||||
logWithCommand.Info("starting up HTTP server")
|
||||
handler := rpc.NewServer()
|
||||
if _, _, err := node.StartHTTPEndpoint(httpPath, rpc.HTTPTimeouts{}, handler); err != nil {
|
||||
_, err := srpc.StartHTTPEndpoint(httpPath, serv.APIs(), []string{"statediff"}, nil, []string{"*"}, rpc.HTTPTimeouts{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
logWithCommand.Info("HTTP server is disabled")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func chainConfig(chainID uint64) (*params.ChainConfig, error) {
|
||||
switch chainID {
|
||||
case 1:
|
||||
return params.MainnetChainConfig, nil
|
||||
case 3:
|
||||
return params.RopstenChainConfig, nil // Ropsten
|
||||
case 4:
|
||||
return params.RinkebyChainConfig, nil
|
||||
case 5:
|
||||
return params.GoerliChainConfig, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("chain config for chainid %d not available", chainID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright © 2022 Vulcanize, Inc
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// statsCmd represents the serve command
|
||||
var statsCmd = &cobra.Command{
|
||||
Use: "stats",
|
||||
Short: "Report stats for cold DB",
|
||||
Long: `Usage
|
||||
|
||||
./eth-statediff-service stats --config={path to toml config file}`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
subCommand = cmd.CalledAs()
|
||||
logWithCommand = *logrus.WithField("SubCommand", subCommand)
|
||||
stats()
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(statsCmd)
|
||||
}
|
||||
|
||||
func stats() {
|
||||
logWithCommand.Info("Running eth-statediff-service stats command")
|
||||
|
||||
reader, _, _ := createReader()
|
||||
reportLatestBlock(reader)
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
statediff "github.com/cerc-io/plugeth-statediff"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/node"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/shared"
|
||||
"github.com/cerc-io/plugeth-statediff/utils"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/triedb"
|
||||
"github.com/ethereum/go-ethereum/triedb/hashdb"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
pkg "github.com/cerc-io/eth-statediff-service/pkg"
|
||||
"github.com/cerc-io/eth-statediff-service/pkg/prom"
|
||||
)
|
||||
|
||||
type blockRange [2]uint64
|
||||
|
||||
func createStateDiffService(lvlDBReader pkg.Reader, chainConf *params.ChainConfig, nodeInfo node.Info) (*pkg.Service, error) {
|
||||
// create statediff service
|
||||
logWithCommand.Debug("Setting up database")
|
||||
conf, err := getConfig(nodeInfo)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
logWithCommand.Debug("Creating statediff indexer")
|
||||
db, indexer, err := indexer.NewStateDiffIndexer(context.Background(), chainConf, nodeInfo, conf, true)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
if conf.Type() == shared.POSTGRES && viper.GetBool("prom.dbStats") {
|
||||
prom.RegisterDBCollector(viper.GetString("database.name"), db)
|
||||
}
|
||||
|
||||
logWithCommand.Debug("Creating statediff service")
|
||||
sdConf := pkg.ServiceConfig{
|
||||
ServiceWorkers: viper.GetUint("statediff.serviceWorkers"),
|
||||
TrieWorkers: viper.GetUint("statediff.trieWorkers"),
|
||||
WorkerQueueSize: viper.GetUint("statediff.workerQueueSize"),
|
||||
PreRuns: setupPreRunRanges(),
|
||||
}
|
||||
return pkg.NewStateDiffService(lvlDBReader, indexer, sdConf), nil
|
||||
}
|
||||
|
||||
func setupPreRunRanges() []pkg.RangeRequest {
|
||||
if !viper.GetBool("statediff.prerun") {
|
||||
return nil
|
||||
}
|
||||
preRunParams := statediff.Params{
|
||||
IncludeBlock: viper.GetBool("prerun.params.includeBlock"),
|
||||
IncludeReceipts: viper.GetBool("prerun.params.includeReceipts"),
|
||||
IncludeTD: viper.GetBool("prerun.params.includeTD"),
|
||||
IncludeCode: viper.GetBool("prerun.params.includeCode"),
|
||||
}
|
||||
var addrStrs []string
|
||||
viper.UnmarshalKey("prerun.params.watchedAddresses", &addrStrs)
|
||||
addrs := make([]common.Address, len(addrStrs))
|
||||
for i, addrStr := range addrStrs {
|
||||
addrs[i] = common.HexToAddress(addrStr)
|
||||
}
|
||||
preRunParams.WatchedAddresses = addrs
|
||||
var rawRanges []blockRange
|
||||
viper.UnmarshalKey("prerun.ranges", &rawRanges)
|
||||
blockRanges := make([]pkg.RangeRequest, len(rawRanges))
|
||||
for i, rawRange := range rawRanges {
|
||||
blockRanges[i] = pkg.RangeRequest{
|
||||
Start: rawRange[0],
|
||||
Stop: rawRange[1],
|
||||
Params: preRunParams,
|
||||
}
|
||||
}
|
||||
if viper.IsSet("prerun.start") && viper.IsSet("prerun.stop") {
|
||||
hardStart := viper.GetInt("prerun.start")
|
||||
hardStop := viper.GetInt("prerun.stop")
|
||||
blockRanges = append(blockRanges, pkg.RangeRequest{
|
||||
Start: uint64(hardStart),
|
||||
Stop: uint64(hardStop),
|
||||
Params: preRunParams,
|
||||
})
|
||||
}
|
||||
|
||||
return blockRanges
|
||||
}
|
||||
|
||||
func createReader() (pkg.Reader, *params.ChainConfig, node.Info) {
|
||||
// load some necessary params
|
||||
logWithCommand.Debug("Loading statediff service parameters")
|
||||
path := viper.GetString("ethdb.path")
|
||||
ancientPath := viper.GetString("ethdb.ancient")
|
||||
url := viper.GetString("ethdb.url")
|
||||
|
||||
if path == "" {
|
||||
logWithCommand.Fatal("Require a valid Ethereum chain data path")
|
||||
}
|
||||
if ancientPath == "" {
|
||||
ancientPath = path + "/ancient"
|
||||
}
|
||||
|
||||
nodeInfo := getEthNodeInfo()
|
||||
|
||||
chainConfigPath := viper.GetString("ethereum.chainConfig")
|
||||
chainConf, err := utils.LoadConfig(chainConfigPath)
|
||||
if err != nil {
|
||||
logWithCommand.Fatalf("Unable to instantiate chain config: %s", err)
|
||||
}
|
||||
|
||||
logWithCommand.Debug("Creating DB reader")
|
||||
readerConf := pkg.EthDBReaderConfig{
|
||||
TrieConfig: &triedb.Config{
|
||||
Preimages: false,
|
||||
IsVerkle: false,
|
||||
HashDB: &hashdb.Config{
|
||||
CleanCacheSize: viper.GetInt("cache.trie"),
|
||||
},
|
||||
},
|
||||
ChainConfig: chainConf,
|
||||
Path: path,
|
||||
AncientPath: ancientPath,
|
||||
Url: url,
|
||||
DBCacheSize: viper.GetInt("cache.database"),
|
||||
}
|
||||
reader, err := pkg.NewEthDBReader(readerConf)
|
||||
if err != nil {
|
||||
logWithCommand.Fatalf("Unable to instantiate DB reader: %s", err)
|
||||
}
|
||||
return reader, chainConf, nodeInfo
|
||||
}
|
||||
|
||||
// report latest block info
|
||||
func reportLatestBlock(reader pkg.Reader) {
|
||||
header, err := reader.GetLatestHeader()
|
||||
if err != nil {
|
||||
logWithCommand.Fatalf("Unable to determine latest header height and hash: %s", err.Error())
|
||||
}
|
||||
if header.Number == nil {
|
||||
logWithCommand.Fatal("Latest header found in DB has a nil block height")
|
||||
}
|
||||
logWithCommand.
|
||||
WithField("height", header.Number).
|
||||
WithField("hash", header.Hash()).
|
||||
Info("Latest block found in DB")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2021 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
v "github.com/cerc-io/eth-statediff-service/version"
|
||||
)
|
||||
|
||||
// versionCmd represents the version command
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Prints the version of eth-statediff-service",
|
||||
Long: `Use this command to fetch the version of eth-statediff-service
|
||||
|
||||
Usage: ./eth-statediff-service version`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
subCommand = cmd.CalledAs()
|
||||
logWithCommand = *log.WithField("SubCommand", subCommand)
|
||||
logWithCommand.Infof("eth-statediff-service version: %s", v.Version)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
// Copyright © 2019 Vulcanize, Inc
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
gethsd "github.com/ethereum/go-ethereum/statediff"
|
||||
ind "github.com/ethereum/go-ethereum/statediff/indexer"
|
||||
"github.com/ethereum/go-ethereum/statediff/indexer/postgres"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
sd "github.com/vulcanize/eth-statediff-service/pkg"
|
||||
)
|
||||
|
||||
var writeCmd = &cobra.Command{
|
||||
Use: "write",
|
||||
Short: "Write statediffs directly to DB for preconfigured block ranges",
|
||||
Long: `Usage
|
||||
|
||||
./eth-statediff-service write --config={path to toml config file}`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
subCommand = cmd.CalledAs()
|
||||
logWithCommand = *logrus.WithField("SubCommand", subCommand)
|
||||
write()
|
||||
},
|
||||
}
|
||||
|
||||
type blockRange [2]uint64
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(writeCmd)
|
||||
writeCmd.PersistentFlags().String("write-api", "", "starts a server which handles write request through endpoints")
|
||||
viper.BindPFlag("write.serve", writeCmd.PersistentFlags().Lookup("write-api"))
|
||||
}
|
||||
|
||||
func write() {
|
||||
logWithCommand.Info("Starting statediff writer")
|
||||
// load params
|
||||
viper.BindEnv("write.serve", WRITE_SERVER)
|
||||
addr := viper.GetString("write.serve")
|
||||
path := viper.GetString("leveldb.path")
|
||||
ancientPath := viper.GetString("leveldb.ancient")
|
||||
if path == "" || ancientPath == "" {
|
||||
logWithCommand.Fatal("require a valid eth leveldb primary datastore path and ancient datastore path")
|
||||
}
|
||||
|
||||
nodeInfo := GetEthNodeInfo()
|
||||
config, err := chainConfig(nodeInfo.ChainID)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
// create leveldb reader
|
||||
logWithCommand.Info("Creating leveldb reader")
|
||||
conf := sd.ReaderConfig{
|
||||
TrieConfig: &trie.Config{
|
||||
Cache: viper.GetInt("cache.trie"),
|
||||
Journal: "",
|
||||
Preimages: false,
|
||||
},
|
||||
ChainConfig: config,
|
||||
Path: path,
|
||||
AncientPath: ancientPath,
|
||||
DBCacheSize: viper.GetInt("cache.database"),
|
||||
}
|
||||
lvlDBReader, err := sd.NewLvlDBReader(conf)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
// create statediff service
|
||||
logWithCommand.Info("Creating statediff service")
|
||||
db, err := postgres.NewDB(postgres.DbConnectionString(GetDBParams()), GetDBConfig(), nodeInfo)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
indexer, err := ind.NewStateDiffIndexer(config, db)
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
statediffService, err := sd.NewStateDiffService(lvlDBReader, indexer, viper.GetUint("statediff.workers"))
|
||||
if err != nil {
|
||||
logWithCommand.Fatal(err)
|
||||
}
|
||||
|
||||
// Read all defined block ranges, write statediffs to database
|
||||
var blockRanges []blockRange
|
||||
diffParams := gethsd.Params{ // todo: configurable?
|
||||
IntermediateStateNodes: true,
|
||||
IntermediateStorageNodes: true,
|
||||
IncludeBlock: true,
|
||||
IncludeReceipts: true,
|
||||
IncludeTD: true,
|
||||
IncludeCode: true,
|
||||
}
|
||||
viper.UnmarshalKey("write.ranges", &blockRanges)
|
||||
viper.UnmarshalKey("write.params", &diffParams)
|
||||
|
||||
blockRangesCh := make(chan blockRange, 100)
|
||||
go func() {
|
||||
for _, r := range blockRanges {
|
||||
blockRangesCh <- r
|
||||
}
|
||||
if addr == "" {
|
||||
close(blockRangesCh)
|
||||
return
|
||||
}
|
||||
startServer(addr, blockRangesCh)
|
||||
}()
|
||||
|
||||
processRanges(statediffService, diffParams, blockRangesCh)
|
||||
}
|
||||
|
||||
func startServer(addr string, blockRangesCh chan<- blockRange) {
|
||||
handler := func(w http.ResponseWriter, req *http.Request) {
|
||||
start, err := strconv.Atoi(req.URL.Query().Get("start"))
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to parse start value: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
end, err := strconv.Atoi(req.URL.Query().Get("end"))
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("failed to parse end value: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case blockRangesCh <- blockRange{uint64(start), uint64(end)}:
|
||||
case <-time.After(time.Millisecond * 200):
|
||||
http.Error(w, "server is busy", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "added block range to the queue\n")
|
||||
}
|
||||
|
||||
http.HandleFunc("/writeDiff", handler)
|
||||
logrus.Fatal(http.ListenAndServe(addr, nil))
|
||||
}
|
||||
|
||||
type diffService interface {
|
||||
WriteStateDiffAt(blockNumber uint64, params gethsd.Params) error
|
||||
}
|
||||
|
||||
func processRanges(sds diffService, param gethsd.Params, blockRangesCh chan blockRange) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for rng := range blockRangesCh {
|
||||
if rng[1] < rng[0] {
|
||||
logWithCommand.Fatal("range ending block number needs to be greater than starting block number")
|
||||
}
|
||||
logrus.Infof("Writing statediffs from block %d to %d", rng[0], rng[1])
|
||||
for height := rng[0]; height <= rng[1]; height++ {
|
||||
err := sds.WriteStateDiffAt(height, param)
|
||||
if err != nil {
|
||||
logrus.Errorf("failed to write state diff for range: %v %v", rng, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gethsd "github.com/ethereum/go-ethereum/statediff"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type mockService struct {
|
||||
reqCount int
|
||||
}
|
||||
|
||||
func (ms *mockService) WriteStateDiffAt(_ uint64, _ gethsd.Params) error {
|
||||
ms.reqCount++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestProcessRanges(t *testing.T) {
|
||||
blockRangesCh := make(chan blockRange)
|
||||
srv := new(mockService)
|
||||
|
||||
go func() {
|
||||
blockRangesCh <- blockRange{uint64(1), uint64(5)}
|
||||
blockRangesCh <- blockRange{uint64(8), uint64(10)}
|
||||
blockRangesCh <- blockRange{uint64(6), uint64(7)}
|
||||
blockRangesCh <- blockRange{uint64(50), uint64(100)}
|
||||
blockRangesCh <- blockRange{uint64(5), uint64(8)}
|
||||
close(blockRangesCh)
|
||||
}()
|
||||
|
||||
processRanges(srv, gethsd.Params{}, blockRangesCh)
|
||||
require.Equal(t, 65, srv.reqCount)
|
||||
}
|
||||
|
||||
func TestHttpEndpoint(t *testing.T) {
|
||||
addr := ":11111"
|
||||
queueSize := 5
|
||||
blockRangesCh := make(chan blockRange, queueSize)
|
||||
srv := new(mockService)
|
||||
|
||||
go startServer(addr, blockRangesCh)
|
||||
|
||||
go func() {
|
||||
br := []blockRange{
|
||||
{uint64(1), uint64(5)},
|
||||
{uint64(8), uint64(10)},
|
||||
{uint64(6), uint64(7)},
|
||||
{uint64(50), uint64(100)},
|
||||
{uint64(5), uint64(8)},
|
||||
// Below request should fail since server has queue size of 5
|
||||
{uint64(52), uint64(328)},
|
||||
{uint64(35), uint64(428)},
|
||||
{uint64(45), uint64(844)},
|
||||
}
|
||||
|
||||
for idx, r := range br {
|
||||
res, err := http.Get(fmt.Sprintf("http://localhost:11111/writeDiff?start=%d&end=%d", r[0], r[1]))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res)
|
||||
if idx < queueSize {
|
||||
require.Equal(t, res.StatusCode, 200)
|
||||
} else {
|
||||
require.Equal(t, res.StatusCode, 500)
|
||||
}
|
||||
require.NoError(t, res.Body.Close())
|
||||
}
|
||||
processRanges(srv, gethsd.Params{}, blockRangesCh)
|
||||
}()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
require.Equal(t, 65, srv.reqCount)
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
version: '3.2'
|
||||
|
||||
services:
|
||||
eth-statediff-service:
|
||||
build:
|
||||
context: ./
|
||||
cache_from:
|
||||
- alpine:latest
|
||||
- golang:1.13
|
||||
dockerfile: ./Dockerfile
|
||||
args:
|
||||
USER: "vdbm"
|
||||
CONFIG_FILE: ./environments/example.toml
|
||||
EXPOSE_PORT: 8545
|
||||
environment:
|
||||
- VDB_COMMAND=serve
|
||||
volumes:
|
||||
- eth-statediff-service-data:/root/.ethereum/
|
||||
ports:
|
||||
- "127.0.0.1:8545:8545"
|
||||
|
||||
volumes:
|
||||
eth-statediff-service-data:
|
||||
@@ -0,0 +1,80 @@
|
||||
[ethdb]
|
||||
path = "/app/geth-rw/chaindata" # ETHDB_PATH
|
||||
ancient = "/app/geth-rw/chaindata/ancient" # ETHDB_ANCIENT
|
||||
|
||||
[server]
|
||||
ipcPath = ".ipc" # SERVICE_IPC_PATH
|
||||
httpPath = "0.0.0.0:8545" # SERVICE_HTTP_PATH
|
||||
|
||||
[statediff]
|
||||
prerun = true # STATEDIFF_PRERUN
|
||||
serviceWorkers = 1 # STATEDIFF_SERVICE_WORKERS
|
||||
workerQueueSize = 1024 # STATEDIFF_WORKER_QUEUE_SIZE
|
||||
trieWorkers = 16 # STATEDIFF_TRIE_WORKERS
|
||||
|
||||
[prerun]
|
||||
only = true # PRERUN_ONLY
|
||||
parallel = true # PRERUN_PARALLEL
|
||||
ranges = []
|
||||
|
||||
# statediffing params for prerun
|
||||
[prerun.params]
|
||||
includeBlock = true # PRERUN_INCLUDE_BLOCK
|
||||
includeReceipts = true # PRERUN_INCLUDE_RECEIPTS
|
||||
includeTD = true # PRERUN_INCLUDE_TD
|
||||
includeCode = true # PRERUN_INCLUDE_CODE
|
||||
watchedAddresses = []
|
||||
|
||||
[log]
|
||||
# Leave empty to output to stdout
|
||||
file = "" # LOG_FILE
|
||||
level = "debug" # LOG_LEVEL
|
||||
|
||||
[database]
|
||||
# output type <postgres | file | dump>
|
||||
type = "postgres"
|
||||
name = "" # DATABASE_NAME
|
||||
hostname = "" # DATABASE_HOSTNAME
|
||||
port = 5432 # DATABASE_PORT
|
||||
user = "" # DATABASE_USER
|
||||
password = "" # DATABASE_PASSWORD
|
||||
driver = "" # DATABASE_DRIVER_TYPE
|
||||
|
||||
# with file type
|
||||
# file mode <sql | csv>
|
||||
fileMode = "csv" # DATABASE_FILE_MODE
|
||||
|
||||
# with SQL file mode
|
||||
filePath = "" # DATABASE_FILE_PATH
|
||||
|
||||
# with CSV file mode
|
||||
fileCsvDir = "" # DATABASE_FILE_CSV_DIR
|
||||
|
||||
# with dump type
|
||||
# <stdout | stderr | discard>
|
||||
dumpDestination = "" # DATABASE_DUMP_DST
|
||||
|
||||
[cache]
|
||||
# settings for geth internal caches
|
||||
database = 1024 # DB_CACHE_SIZE_MB
|
||||
trie = 4096 # TRIE_CACHE_SIZE_MB
|
||||
|
||||
[prom]
|
||||
# prometheus metrics
|
||||
metrics = true # PROM_METRICS
|
||||
http = true # PROM_HTTP
|
||||
httpAddr = "localhost" # PROM_HTTP_ADDR
|
||||
httpPort = "8889" # PROM_HTTP_PORT
|
||||
dbStats = true # PROM_DB_STATS
|
||||
|
||||
[ethereum]
|
||||
# Identifiers for ethereum node
|
||||
nodeID = "" # ETH_NODE_ID
|
||||
clientName = "eth-statediff-service" # ETH_CLIENT_NAME
|
||||
networkID = 1 # ETH_NETWORK_ID
|
||||
chainID = 1 # ETH_CHAIN_ID
|
||||
genesisBlock = "" # ETH_GENESIS_BLOCK
|
||||
chainConfig = "" # ETH_CHAIN_CONFIG
|
||||
|
||||
[debug]
|
||||
pprof = false # DEBUG_PPROF
|
||||
+86
-21
@@ -1,34 +1,99 @@
|
||||
[leveldb]
|
||||
path = "/Users/user/Library/Ethereum/geth/chaindata"
|
||||
ancient = "/Users/user/Library/Ethereum/geth/chaindata/ancient"
|
||||
[ethdb]
|
||||
# # access mode <local | remote>
|
||||
# mode = "local" # ETHDB_MODE
|
||||
|
||||
# Ethdb paths (local mode)
|
||||
path = "/Users/user/Library/Ethereum/geth/chaindata" # ETHDB_PATH
|
||||
ancient = "/Users/user/Library/Ethereum/geth/chaindata/ancient" # ETHDB_ANCIENT
|
||||
|
||||
[server]
|
||||
ipcPath = ".ipc"
|
||||
httpPath = "127.0.0.1:8545"
|
||||
ipcPath = ".ipc" # SERVICE_IPC_PATH
|
||||
httpPath = "127.0.0.1:8545" # SERVICE_HTTP_PATH
|
||||
|
||||
[statediff]
|
||||
workers = 4
|
||||
prerun = true # STATEDIFF_PRERUN
|
||||
serviceWorkers = 1 # STATEDIFF_SERVICE_WORKERS
|
||||
workerQueueSize = 1024 # STATEDIFF_WORKER_QUEUE_SIZE
|
||||
trieWorkers = 4 # STATEDIFF_TRIE_WORKERS
|
||||
|
||||
[write]
|
||||
[prerun]
|
||||
only = false # PRERUN_ONLY
|
||||
parallel = true # PRERUN_PARALLEL
|
||||
|
||||
# to perform prerun in a specific range (optional)
|
||||
start = 0 # PRERUN_RANGE_START
|
||||
stop = 100 # PRERUN_RANGE_STOP
|
||||
|
||||
# to perform prerun over multiple ranges (optional)
|
||||
ranges = [
|
||||
[0, 0]
|
||||
[101, 1000]
|
||||
]
|
||||
serve = ":8888"
|
||||
|
||||
# statediffing params for prerun
|
||||
[prerun.params]
|
||||
includeBlock = true # PRERUN_INCLUDE_BLOCK
|
||||
includeReceipts = true # PRERUN_INCLUDE_RECEIPTS
|
||||
includeTD = true # PRERUN_INCLUDE_TD
|
||||
includeCode = true # PRERUN_INCLUDE_CODE
|
||||
watchedAddresses = []
|
||||
|
||||
[log]
|
||||
file = ""
|
||||
level = "info"
|
||||
|
||||
[eth]
|
||||
chainID = 1
|
||||
# Leave empty to output to stdout
|
||||
file = "" # LOG_FILE
|
||||
level = "info" # LOG_LEVEL
|
||||
|
||||
[database]
|
||||
name = "vulcanize_test"
|
||||
hostname = "localhost"
|
||||
port = 5432
|
||||
user = "vulcanize"
|
||||
password = "..."
|
||||
# output type <postgres | file | dump>
|
||||
type = "postgres"
|
||||
|
||||
# with postgres type
|
||||
# db credentials
|
||||
name = "vulcanize_test" # DATABASE_NAME
|
||||
hostname = "localhost" # DATABASE_HOSTNAME
|
||||
port = 5432 # DATABASE_PORT
|
||||
user = "vulcanize" # DATABASE_USER
|
||||
password = "..." # DATABASE_PASSWORD
|
||||
# SQL backend to use: <sqlx | pgx>
|
||||
driver = "sqlx" # DATABASE_DRIVER_TYPE
|
||||
|
||||
# with file type
|
||||
# file mode <sql | csv>
|
||||
fileMode = "csv" # DATABASE_FILE_MODE
|
||||
|
||||
# with SQL file mode
|
||||
filePath = "" # DATABASE_FILE_PATH
|
||||
|
||||
# with CSV file mode
|
||||
fileCsvDir = "output_dir" # DATABASE_FILE_CSV_DIR
|
||||
|
||||
# with dump type
|
||||
# <stdout | stderr | discard>
|
||||
dumpDestination = "" # DATABASE_DUMP_DST
|
||||
|
||||
[cache]
|
||||
database = 1024
|
||||
trie = 1024
|
||||
# settings for geth internal caches
|
||||
database = 1024 # DB_CACHE_SIZE_MB
|
||||
trie = 1024 # TRIE_CACHE_SIZE_MB
|
||||
|
||||
[prom]
|
||||
# prometheus metrics
|
||||
metrics = true # PROM_METRICS
|
||||
http = true # PROM_HTTP
|
||||
httpAddr = "localhost" # PROM_HTTP_ADDR
|
||||
httpPort = "8889" # PROM_HTTP_PORT
|
||||
dbStats = true # PROM_DB_STATS
|
||||
|
||||
[ethereum]
|
||||
# Identifiers for ethereum node
|
||||
nodeID = "" # ETH_NODE_ID
|
||||
clientName = "eth-statediff-service" # ETH_CLIENT_NAME
|
||||
networkID = 1 # ETH_NETWORK_ID
|
||||
chainID = 1 # ETH_CHAIN_ID
|
||||
genesisBlock = "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" # ETH_GENESIS_BLOCK
|
||||
|
||||
# Path to custom chain config file (optional)
|
||||
# chainID should match that in this config file
|
||||
chainConfig = "chain.json" # ETH_CHAIN_CONFIG
|
||||
|
||||
[debug]
|
||||
pprof = false # DEBUG_PPROF
|
||||
|
||||
@@ -1,14 +1,148 @@
|
||||
module github.com/vulcanize/eth-statediff-service
|
||||
module github.com/cerc-io/eth-statediff-service
|
||||
|
||||
go 1.13
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/ethereum/go-ethereum v1.10.9
|
||||
github.com/sirupsen/logrus v1.7.0
|
||||
github.com/spf13/cobra v1.1.1
|
||||
github.com/spf13/viper v1.7.1
|
||||
github.com/stretchr/testify v1.7.0
|
||||
github.com/vulcanize/go-eth-state-node-iterator v0.0.1-alpha.0.20211014064906-d23d01ed8191
|
||||
github.com/cerc-io/plugeth-statediff v0.3.0
|
||||
github.com/ethereum/go-ethereum v1.14.5
|
||||
github.com/prometheus/client_golang v1.16.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.5.0
|
||||
github.com/spf13/viper v1.10.1
|
||||
)
|
||||
|
||||
replace github.com/ethereum/go-ethereum v1.10.9 => github.com/vulcanize/go-ethereum v1.10.10-statediff-0.0.27
|
||||
require (
|
||||
github.com/DataDog/zstd v1.5.5 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/VictoriaMetrics/fastcache v1.12.2 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.10.0 // indirect
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
|
||||
github.com/cerc-io/eth-iterator-utils v0.2.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cockroachdb/errors v1.11.1 // indirect
|
||||
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
|
||||
github.com/cockroachdb/pebble v1.1.0 // indirect
|
||||
github.com/cockroachdb/redact v1.1.5 // indirect
|
||||
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect
|
||||
github.com/consensys/bavard v0.1.13 // indirect
|
||||
github.com/consensys/gnark-crypto v0.12.1 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240223125850-b1e8a79f509c // indirect
|
||||
github.com/crate-crypto/go-kzg-4844 v1.0.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
|
||||
github.com/deepmap/oapi-codegen v1.8.2 // indirect
|
||||
github.com/ethereum/c-kzg-4844 v1.0.0 // indirect
|
||||
github.com/ethereum/go-verkle v0.1.1-0.20240306133620-7d920df305f0 // indirect
|
||||
github.com/ferranbt/fastssz v0.1.2 // indirect
|
||||
github.com/fjl/memsize v0.0.2 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect
|
||||
github.com/georgysavva/scany v0.2.9 // indirect
|
||||
github.com/getsentry/sentry-go v0.22.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-stack/stack v1.8.1 // indirect
|
||||
github.com/gofrs/flock v0.8.1 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.0 // indirect
|
||||
github.com/graph-gophers/graphql-go v1.3.0 // indirect
|
||||
github.com/hashicorp/go-bexpr v0.1.12 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 // indirect
|
||||
github.com/holiman/bloomfilter/v2 v2.0.3 // indirect
|
||||
github.com/holiman/uint256 v1.2.4 // indirect
|
||||
github.com/huin/goupnp v1.3.0 // indirect
|
||||
github.com/inconshreveable/log15 v2.16.0+incompatible // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/influxdata/influxdb-client-go/v2 v2.4.0 // indirect
|
||||
github.com/influxdata/influxdb1-client v0.0.0-20220302092344-a9ab5670611c // indirect
|
||||
github.com/influxdata/line-protocol v0.0.0-20210311194329-9aa0e372d097 // indirect
|
||||
github.com/ipfs/go-cid v0.4.1 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.10.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.1.1 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.8.1 // indirect
|
||||
github.com/jackc/pgx/v4 v4.13.0 // indirect
|
||||
github.com/jackc/puddle v1.1.3 // indirect
|
||||
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
|
||||
github.com/jmoiron/sqlx v1.2.0 // indirect
|
||||
github.com/klauspost/compress v1.16.7 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/magiconair/properties v1.8.5 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/minio/sha256-simd v1.0.1 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/mitchellh/pointerstructure v1.2.1 // indirect
|
||||
github.com/mmcloughlin/addchain v0.4.0 // indirect
|
||||
github.com/mr-tron/base58 v1.2.0 // indirect
|
||||
github.com/multiformats/go-base32 v0.1.0 // indirect
|
||||
github.com/multiformats/go-base36 v0.2.0 // indirect
|
||||
github.com/multiformats/go-multibase v0.2.0 // indirect
|
||||
github.com/multiformats/go-multihash v0.2.3 // indirect
|
||||
github.com/multiformats/go-varint v0.0.7 // indirect
|
||||
github.com/olekukonko/tablewriter v0.0.5 // indirect
|
||||
github.com/openrelayxyz/plugeth-utils v1.5.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pelletier/go-toml v1.9.4 // indirect
|
||||
github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7 // indirect
|
||||
github.com/pganalyze/pg_query_go/v4 v4.2.1 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_model v0.4.0 // indirect
|
||||
github.com/prometheus/common v0.44.0 // indirect
|
||||
github.com/prometheus/procfs v0.11.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.4 // indirect
|
||||
github.com/rogpeppe/go-internal v1.12.0 // indirect
|
||||
github.com/rs/cors v1.9.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/shirou/gopsutil v3.21.11+incompatible // indirect
|
||||
github.com/shopspring/decimal v1.2.0 // indirect
|
||||
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||
github.com/spf13/afero v1.6.0 // indirect
|
||||
github.com/spf13/cast v1.4.1 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/status-im/keycard-go v0.2.0 // indirect
|
||||
github.com/stretchr/objx v0.5.0 // indirect
|
||||
github.com/stretchr/testify v1.8.4 // indirect
|
||||
github.com/subosito/gotenv v1.2.0 // indirect
|
||||
github.com/supranational/blst v0.3.11 // indirect
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20220614013038-64ee5596c38a // indirect
|
||||
github.com/thoas/go-funk v0.9.3 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
|
||||
github.com/urfave/cli/v2 v2.25.7 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
golang.org/x/crypto v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa // indirect
|
||||
golang.org/x/net v0.24.0 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/term v0.19.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
golang.org/x/time v0.5.0 // indirect
|
||||
google.golang.org/protobuf v1.33.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
lukechampine.com/blake3 v1.2.1 // indirect
|
||||
rsc.io/tmplfunc v0.0.3 // indirect
|
||||
)
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/vulcanize/eth-statediff-service/cmd"
|
||||
import "github.com/cerc-io/eth-statediff-service/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
{
|
||||
"annotations": {
|
||||
"list": [
|
||||
{
|
||||
"builtIn": 1,
|
||||
"datasource": "-- Grafana --",
|
||||
"enable": true,
|
||||
"hide": true,
|
||||
"iconColor": "rgba(0, 211, 255, 1)",
|
||||
"name": "Annotations & Alerts",
|
||||
"type": "dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"editable": true,
|
||||
"gnetId": null,
|
||||
"graphTooltip": 0,
|
||||
"id": 4,
|
||||
"iteration": 1635774999288,
|
||||
"links": [
|
||||
{
|
||||
"icon": "info",
|
||||
"tags": [],
|
||||
"targetBlank": true,
|
||||
"title": "Grafana Docs",
|
||||
"tooltip": "",
|
||||
"type": "link",
|
||||
"url": "https://grafana.com/docs/grafana/latest/"
|
||||
},
|
||||
{
|
||||
"icon": "info",
|
||||
"tags": [],
|
||||
"targetBlank": true,
|
||||
"title": "Prometheus Docs",
|
||||
"type": "link",
|
||||
"url": "http://prometheus.io/docs/introduction/overview/"
|
||||
}
|
||||
],
|
||||
"panels": [
|
||||
{
|
||||
"aliasColors": {},
|
||||
"bars": false,
|
||||
"dashLength": 10,
|
||||
"dashes": false,
|
||||
"datasource": "eth-statediff-service",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {},
|
||||
"links": [],
|
||||
"mappings": [],
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 80
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"fill": 1,
|
||||
"fillGradient": 0,
|
||||
"gridPos": {
|
||||
"h": 6,
|
||||
"w": 18,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"hiddenSeries": false,
|
||||
"id": 3,
|
||||
"legend": {
|
||||
"avg": false,
|
||||
"current": false,
|
||||
"max": false,
|
||||
"min": false,
|
||||
"show": true,
|
||||
"total": false,
|
||||
"values": false
|
||||
},
|
||||
"lines": true,
|
||||
"linewidth": 1,
|
||||
"links": [],
|
||||
"nullPointMode": "null",
|
||||
"percentage": false,
|
||||
"pluginVersion": "7.1.5",
|
||||
"pointradius": 2,
|
||||
"points": false,
|
||||
"renderer": "flot",
|
||||
"seriesOverrides": [],
|
||||
"spaceLength": 10,
|
||||
"stack": false,
|
||||
"steppedLine": false,
|
||||
"targets": [
|
||||
{
|
||||
"expr": "rate(eth_statediff_service_processed_height{instance=\"$instance\"}[1m])",
|
||||
"interval": "",
|
||||
"legendFormat": "",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"thresholds": [],
|
||||
"timeFrom": null,
|
||||
"timeRegions": [],
|
||||
"timeShift": null,
|
||||
"title": "Instance block processed (rate-1m)",
|
||||
"tooltip": {
|
||||
"shared": true,
|
||||
"sort": 0,
|
||||
"value_type": "individual"
|
||||
},
|
||||
"type": "graph",
|
||||
"xaxis": {
|
||||
"buckets": null,
|
||||
"mode": "time",
|
||||
"name": null,
|
||||
"show": true,
|
||||
"values": []
|
||||
},
|
||||
"yaxes": [
|
||||
{
|
||||
"format": "short",
|
||||
"label": null,
|
||||
"logBase": 1,
|
||||
"max": null,
|
||||
"min": null,
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"format": "short",
|
||||
"label": null,
|
||||
"logBase": 1,
|
||||
"max": null,
|
||||
"min": null,
|
||||
"show": true
|
||||
}
|
||||
],
|
||||
"yaxis": {
|
||||
"align": false,
|
||||
"alignLevel": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "<span style=\"font-family: 'Open Sans', 'Helvetica Neue', Helvetica; font-size: 25px;vertical-align: text-top;color: #bbbfc2;margin-left: 10px;\">Prometheus</span>\n\n<p style=\"margin-top: 10px;\">You're using Prometheus, an open-source systems monitoring and alerting toolkit originally built at SoundCloud. For more information, check out the <a href=\"https://grafana.com/\">Grafana</a> and <a href=\"http://prometheus.io/\">Prometheus</a> projects.</p>",
|
||||
"datasource": null,
|
||||
"editable": true,
|
||||
"error": false,
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 5,
|
||||
"w": 6,
|
||||
"x": 18,
|
||||
"y": 0
|
||||
},
|
||||
"id": 9,
|
||||
"links": [],
|
||||
"mode": "html",
|
||||
"options": {
|
||||
"content": "<span style=\"font-family: 'Open Sans', 'Helvetica Neue', Helvetica; font-size: 25px;vertical-align: text-top;color: #bbbfc2;margin-left: 10px;\">Prometheus</span>\n\n<p style=\"margin-top: 10px;\">You're using Prometheus, an open-source systems monitoring and alerting toolkit originally built at SoundCloud. For more information, check out the <a href=\"https://grafana.com/\">Grafana</a> and <a href=\"http://prometheus.io/\">Prometheus</a> projects.</p>",
|
||||
"mode": "html"
|
||||
},
|
||||
"pluginVersion": "7.1.0",
|
||||
"style": {},
|
||||
"title": "",
|
||||
"transparent": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"content": "#### Samples Ingested\nThis graph displays the count of samples ingested by the Prometheus server, as measured over the last 5 minutes, per time series in the range vector. When troubleshooting an issue on IRC or Github, this is often the first stat requested by the Prometheus team. ",
|
||||
"datasource": null,
|
||||
"editable": true,
|
||||
"error": false,
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 6,
|
||||
"w": 4,
|
||||
"x": 18,
|
||||
"y": 5
|
||||
},
|
||||
"id": 8,
|
||||
"links": [],
|
||||
"mode": "markdown",
|
||||
"options": {
|
||||
"content": "#### Samples Ingested\nThis graph displays the count of samples ingested by the Prometheus server, as measured over the last 5 minutes, per time series in the range vector. When troubleshooting an issue on IRC or Github, this is often the first stat requested by the Prometheus team. ",
|
||||
"mode": "markdown"
|
||||
},
|
||||
"pluginVersion": "7.1.0",
|
||||
"style": {},
|
||||
"title": "",
|
||||
"transparent": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"aliasColors": {
|
||||
"Value": "red",
|
||||
"aggr": "red"
|
||||
},
|
||||
"bars": false,
|
||||
"dashLength": 10,
|
||||
"dashes": false,
|
||||
"datasource": "eth-statediff-service",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {},
|
||||
"links": [],
|
||||
"mappings": [],
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 80
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"fill": 1,
|
||||
"fillGradient": 0,
|
||||
"gridPos": {
|
||||
"h": 6,
|
||||
"w": 18,
|
||||
"x": 0,
|
||||
"y": 6
|
||||
},
|
||||
"hiddenSeries": false,
|
||||
"id": 17,
|
||||
"legend": {
|
||||
"avg": false,
|
||||
"current": false,
|
||||
"max": false,
|
||||
"min": false,
|
||||
"show": true,
|
||||
"total": false,
|
||||
"values": false
|
||||
},
|
||||
"lines": true,
|
||||
"linewidth": 1,
|
||||
"links": [],
|
||||
"nullPointMode": "null",
|
||||
"percentage": false,
|
||||
"pluginVersion": "7.1.5",
|
||||
"pointradius": 2,
|
||||
"points": false,
|
||||
"renderer": "flot",
|
||||
"seriesOverrides": [],
|
||||
"spaceLength": 10,
|
||||
"stack": false,
|
||||
"steppedLine": false,
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(increase(eth_statediff_service_processed_height{instance=~\".+\"}[1m]))",
|
||||
"interval": "",
|
||||
"legendFormat": "aggr",
|
||||
"refId": "C"
|
||||
}
|
||||
],
|
||||
"thresholds": [],
|
||||
"timeFrom": null,
|
||||
"timeRegions": [],
|
||||
"timeShift": null,
|
||||
"title": "Aggregate block processed (rate-1m)",
|
||||
"tooltip": {
|
||||
"shared": true,
|
||||
"sort": 0,
|
||||
"value_type": "individual"
|
||||
},
|
||||
"type": "graph",
|
||||
"xaxis": {
|
||||
"buckets": null,
|
||||
"mode": "time",
|
||||
"name": null,
|
||||
"show": true,
|
||||
"values": []
|
||||
},
|
||||
"yaxes": [
|
||||
{
|
||||
"format": "short",
|
||||
"label": null,
|
||||
"logBase": 1,
|
||||
"max": null,
|
||||
"min": null,
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"format": "short",
|
||||
"label": null,
|
||||
"logBase": 1,
|
||||
"max": null,
|
||||
"min": null,
|
||||
"show": true
|
||||
}
|
||||
],
|
||||
"yaxis": {
|
||||
"align": false,
|
||||
"alignLevel": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "#### Scrapes\nPrometheus scrapes metrics from instrumented jobs, either directly or via an intermediary push gateway for short-lived jobs. Target scrapes will show how frequently targets are scraped, as measured over the last 5 minutes, per time series in the range vector. Scrape Duration will show how long the scrapes are taking, with percentiles available as series. ",
|
||||
"datasource": null,
|
||||
"editable": true,
|
||||
"error": false,
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 7,
|
||||
"w": 6,
|
||||
"x": 18,
|
||||
"y": 11
|
||||
},
|
||||
"id": 11,
|
||||
"links": [],
|
||||
"mode": "markdown",
|
||||
"options": {
|
||||
"content": "#### Scrapes\nPrometheus scrapes metrics from instrumented jobs, either directly or via an intermediary push gateway for short-lived jobs. Target scrapes will show how frequently targets are scraped, as measured over the last 5 minutes, per time series in the range vector. Scrape Duration will show how long the scrapes are taking, with percentiles available as series. ",
|
||||
"mode": "markdown"
|
||||
},
|
||||
"pluginVersion": "7.1.0",
|
||||
"style": {},
|
||||
"title": "",
|
||||
"transparent": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"content": "#### Rule Evaluation Duration\nThis graph panel plots the duration for all evaluations to execute. The 50th percentile, 90th percentile and 99th percentile are shown as three separate series to help identify outliers that may be skewing the data.",
|
||||
"datasource": null,
|
||||
"editable": true,
|
||||
"error": false,
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"custom": {}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 7,
|
||||
"w": 6,
|
||||
"x": 18,
|
||||
"y": 18
|
||||
},
|
||||
"id": 15,
|
||||
"links": [],
|
||||
"mode": "markdown",
|
||||
"options": {
|
||||
"content": "#### Rule Evaluation Duration\nThis graph panel plots the duration for all evaluations to execute. The 50th percentile, 90th percentile and 99th percentile are shown as three separate series to help identify outliers that may be skewing the data.",
|
||||
"mode": "markdown"
|
||||
},
|
||||
"pluginVersion": "7.1.0",
|
||||
"style": {},
|
||||
"title": "",
|
||||
"transparent": true,
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"refresh": false,
|
||||
"revision": "1.0",
|
||||
"schemaVersion": 26,
|
||||
"style": "dark",
|
||||
"tags": [],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"allValue": null,
|
||||
"current": {
|
||||
"selected": true,
|
||||
"text": "localhost:8888",
|
||||
"value": "localhost:8888"
|
||||
},
|
||||
"datasource": "eth-statediff-service",
|
||||
"definition": "label_values(instance)",
|
||||
"hide": 0,
|
||||
"includeAll": false,
|
||||
"label": "SelectInstance",
|
||||
"multi": false,
|
||||
"name": "instance",
|
||||
"options": [],
|
||||
"query": "label_values(instance)",
|
||||
"refresh": 2,
|
||||
"regex": "",
|
||||
"skipUrlSync": false,
|
||||
"sort": 1,
|
||||
"tagValuesQuery": "",
|
||||
"tags": [],
|
||||
"tagsQuery": "",
|
||||
"type": "query",
|
||||
"useTags": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"time": {
|
||||
"from": "now-30m",
|
||||
"to": "now"
|
||||
},
|
||||
"timepicker": {
|
||||
"now": true,
|
||||
"refresh_intervals": [
|
||||
"5s",
|
||||
"10s",
|
||||
"30s",
|
||||
"1m",
|
||||
"5m",
|
||||
"15m",
|
||||
"30m",
|
||||
"1h",
|
||||
"2h",
|
||||
"1d"
|
||||
],
|
||||
"time_options": [
|
||||
"5m",
|
||||
"15m",
|
||||
"1h",
|
||||
"6h",
|
||||
"12h",
|
||||
"24h",
|
||||
"2d",
|
||||
"7d",
|
||||
"30d"
|
||||
]
|
||||
},
|
||||
"timezone": "browser",
|
||||
"title": "Prometheus Block Process Stats",
|
||||
"uid": "q1FUJHKnz",
|
||||
"version": 14
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
global:
|
||||
scrape_interval: 10s
|
||||
|
||||
scrape_configs:
|
||||
- job_name: 'eth-statediff-service'
|
||||
static_configs:
|
||||
- targets: ['localhost:8100']
|
||||
+9
-9
@@ -18,7 +18,7 @@ package statediff
|
||||
import (
|
||||
"context"
|
||||
|
||||
sd "github.com/ethereum/go-ethereum/statediff"
|
||||
sd "github.com/cerc-io/plugeth-statediff"
|
||||
)
|
||||
|
||||
// APIName is the namespace used for the state diffing service API
|
||||
@@ -28,13 +28,13 @@ const APIName = "statediff"
|
||||
const APIVersion = "0.0.1"
|
||||
|
||||
// PublicStateDiffAPI provides an RPC interface
|
||||
// that can be used to fetch historical diffs from leveldb directly
|
||||
// that can be used to fetch historical diffs from database directly
|
||||
type PublicStateDiffAPI struct {
|
||||
sds IService
|
||||
sds *Service
|
||||
}
|
||||
|
||||
// NewPublicStateDiffAPI creates an rpc interface for the underlying statediff service
|
||||
func NewPublicStateDiffAPI(sds IService) *PublicStateDiffAPI {
|
||||
func NewPublicStateDiffAPI(sds *Service) *PublicStateDiffAPI {
|
||||
return &PublicStateDiffAPI{
|
||||
sds: sds,
|
||||
}
|
||||
@@ -45,12 +45,12 @@ func (api *PublicStateDiffAPI) StateDiffAt(ctx context.Context, blockNumber uint
|
||||
return api.sds.StateDiffAt(blockNumber, params)
|
||||
}
|
||||
|
||||
// StateTrieAt returns a state trie payload at the specific blockheight
|
||||
func (api *PublicStateDiffAPI) StateTrieAt(ctx context.Context, blockNumber uint64, params sd.Params) (*sd.Payload, error) {
|
||||
return api.sds.StateTrieAt(blockNumber, params)
|
||||
}
|
||||
|
||||
// WriteStateDiffAt writes a state diff object directly to DB at the specific blockheight
|
||||
func (api *PublicStateDiffAPI) WriteStateDiffAt(ctx context.Context, blockNumber uint64, params sd.Params) error {
|
||||
return api.sds.WriteStateDiffAt(blockNumber, params)
|
||||
}
|
||||
|
||||
// WriteStateDiffsInRange writes the state diff objects for the provided block range, with the provided params
|
||||
func (api *PublicStateDiffAPI) WriteStateDiffsInRange(ctx context.Context, start, stop uint64, params sd.Params) error {
|
||||
return api.sds.WriteStateDiffsInRange(start, stop, params)
|
||||
}
|
||||
|
||||
-783
@@ -1,783 +0,0 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Contains a batch of utility type declarations used by the tests. As the node
|
||||
// operates on unique types, a lot of them are needed to check various features.
|
||||
|
||||
package statediff
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math/bits"
|
||||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
sd "github.com/ethereum/go-ethereum/statediff"
|
||||
sdtrie "github.com/ethereum/go-ethereum/statediff/trie"
|
||||
sdtypes "github.com/ethereum/go-ethereum/statediff/types"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
|
||||
iter "github.com/vulcanize/go-eth-state-node-iterator"
|
||||
)
|
||||
|
||||
var (
|
||||
nullHashBytes = common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000000")
|
||||
emptyNode, _ = rlp.EncodeToBytes([]byte{})
|
||||
emptyContractRoot = crypto.Keccak256Hash(emptyNode)
|
||||
nullCodeHash = crypto.Keccak256Hash([]byte{}).Bytes()
|
||||
)
|
||||
|
||||
// Builder interface exposes the method for building a state diff between two blocks
|
||||
type Builder interface {
|
||||
BuildStateDiffObject(args sd.Args, params sd.Params) (sd.StateObject, error)
|
||||
BuildStateTrieObject(current *types.Block) (sd.StateObject, error)
|
||||
WriteStateDiffObject(args sd.StateRoots, params sd.Params, output sdtypes.StateNodeSink, codeOutput sdtypes.CodeSink) error
|
||||
}
|
||||
|
||||
type builder struct {
|
||||
stateCache state.Database
|
||||
numWorkers uint
|
||||
}
|
||||
|
||||
type iterPair struct {
|
||||
older, newer trie.NodeIterator
|
||||
}
|
||||
|
||||
func resolveNode(it trie.NodeIterator, trieDB *trie.Database) (sdtypes.StateNode, []interface{}, error) {
|
||||
nodePath := make([]byte, len(it.Path()))
|
||||
copy(nodePath, it.Path())
|
||||
node, err := trieDB.Node(it.Hash())
|
||||
if err != nil {
|
||||
return sdtypes.StateNode{}, nil, err
|
||||
}
|
||||
var nodeElements []interface{}
|
||||
if err := rlp.DecodeBytes(node, &nodeElements); err != nil {
|
||||
return sdtypes.StateNode{}, nil, err
|
||||
}
|
||||
ty, err := sdtrie.CheckKeyType(nodeElements)
|
||||
if err != nil {
|
||||
return sdtypes.StateNode{}, nil, err
|
||||
}
|
||||
return sdtypes.StateNode{
|
||||
NodeType: ty,
|
||||
Path: nodePath,
|
||||
NodeValue: node,
|
||||
}, nodeElements, nil
|
||||
}
|
||||
|
||||
// convenience
|
||||
func stateNodeAppender(nodes *[]sdtypes.StateNode) sdtypes.StateNodeSink {
|
||||
return func(node sdtypes.StateNode) error {
|
||||
*nodes = append(*nodes, node)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func storageNodeAppender(nodes *[]sdtypes.StorageNode) sdtypes.StorageNodeSink {
|
||||
return func(node sdtypes.StorageNode) error {
|
||||
*nodes = append(*nodes, node)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func codeMappingAppender(data *[]sdtypes.CodeAndCodeHash) sdtypes.CodeSink {
|
||||
return func(c sdtypes.CodeAndCodeHash) error {
|
||||
*data = append(*data, c)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// NewBuilder is used to create a statediff builder
|
||||
func NewBuilder(stateCache state.Database, workers uint) (Builder, error) {
|
||||
if workers == 0 {
|
||||
workers = 1
|
||||
}
|
||||
if bits.OnesCount(workers) != 1 {
|
||||
return nil, fmt.Errorf("workers must be a power of 2")
|
||||
}
|
||||
return &builder{
|
||||
stateCache: stateCache, // state cache is safe for concurrent reads
|
||||
numWorkers: workers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BuildStateTrieObject builds a state trie object from the provided block
|
||||
func (sdb *builder) BuildStateTrieObject(current *types.Block) (sd.StateObject, error) {
|
||||
currentTrie, err := sdb.stateCache.OpenTrie(current.Root())
|
||||
if err != nil {
|
||||
return sd.StateObject{}, fmt.Errorf("error creating trie for block %d: %v", current.Number(), err)
|
||||
}
|
||||
it := currentTrie.NodeIterator([]byte{})
|
||||
stateNodes, codeAndCodeHashes, err := sdb.buildStateTrie(it)
|
||||
if err != nil {
|
||||
return sd.StateObject{}, fmt.Errorf("error collecting state nodes for block %d: %v", current.Number(), err)
|
||||
}
|
||||
return sd.StateObject{
|
||||
BlockNumber: current.Number(),
|
||||
BlockHash: current.Hash(),
|
||||
Nodes: stateNodes,
|
||||
CodeAndCodeHashes: codeAndCodeHashes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (sdb *builder) buildStateTrie(it trie.NodeIterator) ([]sdtypes.StateNode, []sdtypes.CodeAndCodeHash, error) {
|
||||
stateNodes := make([]sdtypes.StateNode, 0)
|
||||
codeAndCodeHashes := make([]sdtypes.CodeAndCodeHash, 0)
|
||||
for it.Next(true) {
|
||||
// skip value nodes
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
var account types.StateAccount
|
||||
if err := rlp.DecodeBytes(nodeElements[1].([]byte), &account); err != nil {
|
||||
return nil, nil, fmt.Errorf("error decoding account for leaf node at path %x nerror: %v", node.Path, err)
|
||||
}
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
node.LeafKey = leafKey
|
||||
if !bytes.Equal(account.CodeHash, nullCodeHash) {
|
||||
var storageNodes []sdtypes.StorageNode
|
||||
err := sdb.buildStorageNodesEventual(account.Root, nil, true, storageNodeAppender(&storageNodes))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed building eventual storage diffs for account %+v\r\nerror: %v", account, err)
|
||||
}
|
||||
node.StorageNodes = storageNodes
|
||||
// emit codehash => code mappings for cod
|
||||
codeHash := common.BytesToHash(account.CodeHash)
|
||||
code, err := sdb.stateCache.ContractCode(common.Hash{}, codeHash)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to retrieve code for codehash %s\r\n error: %v", codeHash.String(), err)
|
||||
}
|
||||
codeAndCodeHashes = append(codeAndCodeHashes, sdtypes.CodeAndCodeHash{
|
||||
Hash: codeHash,
|
||||
Code: code,
|
||||
})
|
||||
}
|
||||
stateNodes = append(stateNodes, node)
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
stateNodes = append(stateNodes, node)
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
}
|
||||
return stateNodes, codeAndCodeHashes, it.Error()
|
||||
}
|
||||
|
||||
// BuildStateDiffObject builds a statediff object from two blocks and the provided parameters
|
||||
func (sdb *builder) BuildStateDiffObject(args sd.Args, params sd.Params) (sd.StateObject, error) {
|
||||
var stateNodes []sdtypes.StateNode
|
||||
var codeAndCodeHashes []sdtypes.CodeAndCodeHash
|
||||
err := sdb.WriteStateDiffObject(
|
||||
sd.StateRoots{OldStateRoot: args.OldStateRoot, NewStateRoot: args.NewStateRoot},
|
||||
params, stateNodeAppender(&stateNodes), codeMappingAppender(&codeAndCodeHashes))
|
||||
if err != nil {
|
||||
return sd.StateObject{}, err
|
||||
}
|
||||
return sd.StateObject{
|
||||
BlockHash: args.BlockHash,
|
||||
BlockNumber: args.BlockNumber,
|
||||
Nodes: stateNodes,
|
||||
CodeAndCodeHashes: codeAndCodeHashes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Writes a statediff object to output callback
|
||||
func (sdb *builder) WriteStateDiffObject(args sd.StateRoots, params sd.Params, output sdtypes.StateNodeSink, codeOutput sdtypes.CodeSink) error {
|
||||
if len(params.WatchedAddresses) > 0 {
|
||||
// if we are watching only specific accounts then we are only diffing leaf nodes
|
||||
log.Info("Ignoring intermediate state nodes because WatchedAddresses was passed")
|
||||
params.IntermediateStateNodes = false
|
||||
}
|
||||
|
||||
// Load tries for old and new states
|
||||
oldTrie, err := sdb.stateCache.OpenTrie(args.OldStateRoot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating trie for old state root: %v", err)
|
||||
}
|
||||
newTrie, err := sdb.stateCache.OpenTrie(args.NewStateRoot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating trie for new state root: %v", err)
|
||||
}
|
||||
|
||||
// Split old and new tries into corresponding subtrie iterators
|
||||
oldIterFac := iter.NewSubtrieIteratorFactory(oldTrie, sdb.numWorkers)
|
||||
newIterFac := iter.NewSubtrieIteratorFactory(newTrie, sdb.numWorkers)
|
||||
|
||||
// Create iterators ahead of time to avoid race condition in state.Trie access
|
||||
// We do two state iterations per subtrie: one for new/updated nodes,
|
||||
// one for deleted/updated nodes; prepare 2 iterator instances for each task
|
||||
var iterPairs [][]iterPair
|
||||
for i := uint(0); i < sdb.numWorkers; i++ {
|
||||
iterPairs = append(iterPairs, []iterPair{
|
||||
iterPair{older: oldIterFac.IteratorAt(i), newer: newIterFac.IteratorAt(i)},
|
||||
iterPair{older: oldIterFac.IteratorAt(i), newer: newIterFac.IteratorAt(i)},
|
||||
})
|
||||
}
|
||||
|
||||
// Dispatch workers to process trie data; sync and collect results here via channels
|
||||
nodeChan := make(chan sdtypes.StateNode)
|
||||
codeChan := make(chan sdtypes.CodeAndCodeHash)
|
||||
|
||||
go func() {
|
||||
nodeSender := func(node sdtypes.StateNode) error { nodeChan <- node; return nil }
|
||||
codeSender := func(code sdtypes.CodeAndCodeHash) error { codeChan <- code; return nil }
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for w := uint(0); w < sdb.numWorkers; w++ {
|
||||
wg.Add(1)
|
||||
go func(worker uint) {
|
||||
defer wg.Done()
|
||||
sdb.buildStateDiff(iterPairs[worker], params, nodeSender, codeSender)
|
||||
}(w)
|
||||
}
|
||||
wg.Wait()
|
||||
close(nodeChan)
|
||||
close(codeChan)
|
||||
}()
|
||||
|
||||
for nodeChan != nil || codeChan != nil {
|
||||
select {
|
||||
case node, more := <-nodeChan:
|
||||
if more {
|
||||
if err := output(node); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
nodeChan = nil
|
||||
}
|
||||
case codeAndCodeHash, more := <-codeChan:
|
||||
if more {
|
||||
if err := codeOutput(codeAndCodeHash); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
codeChan = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sdb *builder) buildStateDiff(args []iterPair, params sd.Params, output sdtypes.StateNodeSink, codeOutput sdtypes.CodeSink) error {
|
||||
// collect a slice of all the intermediate nodes that were touched and exist at B
|
||||
// a map of their leafkey to all the accounts that were touched and exist at B
|
||||
// and a slice of all the paths for the nodes in both of the above sets
|
||||
var diffAccountsAtB AccountMap
|
||||
var diffPathsAtB map[string]bool
|
||||
var err error
|
||||
if params.IntermediateStateNodes {
|
||||
diffAccountsAtB, diffPathsAtB, err = sdb.createdAndUpdatedStateWithIntermediateNodes(args[0], output)
|
||||
} else {
|
||||
diffAccountsAtB, diffPathsAtB, err = sdb.createdAndUpdatedState(args[0], params.WatchedAddresses)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("error collecting createdAndUpdatedNodes: %v", err)
|
||||
}
|
||||
|
||||
// collect a slice of all the nodes that existed at a path in A that doesn't exist in B
|
||||
// a map of their leafkey to all the accounts that were touched and exist at A
|
||||
diffAccountsAtA, err := sdb.deletedOrUpdatedState(args[1], diffPathsAtB, output)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error collecting deletedOrUpdatedNodes: %v", err)
|
||||
}
|
||||
|
||||
// collect and sort the leafkey keys for both account mappings into a slice
|
||||
createKeys := sortKeys(diffAccountsAtB)
|
||||
deleteKeys := sortKeys(diffAccountsAtA)
|
||||
|
||||
// and then find the intersection of these keys
|
||||
// these are the leafkeys for the accounts which exist at both A and B but are different
|
||||
// this also mutates the passed in createKeys and deleteKeys, removing the intersection keys
|
||||
// and leaving the truly created or deleted keys in place
|
||||
updatedKeys := findIntersection(createKeys, deleteKeys)
|
||||
|
||||
// build the diff nodes for the updated accounts using the mappings at both A and B as directed by the keys found as the intersection of the two
|
||||
err = sdb.buildAccountUpdates(
|
||||
diffAccountsAtB, diffAccountsAtA, updatedKeys,
|
||||
params.WatchedStorageSlots, params.IntermediateStorageNodes, output)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error building diff for updated accounts: %v", err)
|
||||
}
|
||||
// build the diff nodes for created accounts
|
||||
err = sdb.buildAccountCreations(diffAccountsAtB, params.WatchedStorageSlots, params.IntermediateStorageNodes, output, codeOutput)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error building diff for created accounts: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// createdAndUpdatedState returns
|
||||
// a mapping of their leafkeys to all the accounts that exist in a different state at B than A
|
||||
// and a slice of the paths for all of the nodes included in both
|
||||
func (sdb *builder) createdAndUpdatedState(iters iterPair, watchedAddresses []common.Address) (AccountMap, map[string]bool, error) {
|
||||
diffPathsAtB := make(map[string]bool)
|
||||
diffAcountsAtB := make(AccountMap)
|
||||
it, _ := trie.NewDifferenceIterator(iters.older, iters.newer)
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
// created vs updated is important for leaf nodes since we need to diff their storage
|
||||
// so we need to map all changed accounts at B to their leafkey, since account can change pathes but not leafkey
|
||||
var account types.StateAccount
|
||||
if err := rlp.DecodeBytes(nodeElements[1].([]byte), &account); err != nil {
|
||||
return nil, nil, fmt.Errorf("error decoding account for leaf node at path %x nerror: %v", node.Path, err)
|
||||
}
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
if isWatchedAddress(watchedAddresses, leafKey) {
|
||||
diffAcountsAtB[common.Bytes2Hex(leafKey)] = accountWrapper{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
LeafKey: leafKey,
|
||||
Account: &account,
|
||||
}
|
||||
}
|
||||
}
|
||||
// add both intermediate and leaf node paths to the list of diffPathsAtB
|
||||
diffPathsAtB[common.Bytes2Hex(node.Path)] = true
|
||||
}
|
||||
return diffAcountsAtB, diffPathsAtB, it.Error()
|
||||
}
|
||||
|
||||
// createdAndUpdatedStateWithIntermediateNodes returns
|
||||
// a slice of all the intermediate nodes that exist in a different state at B than A
|
||||
// a mapping of their leafkeys to all the accounts that exist in a different state at B than A
|
||||
// and a slice of the paths for all of the nodes included in both
|
||||
func (sdb *builder) createdAndUpdatedStateWithIntermediateNodes(iters iterPair, output sdtypes.StateNodeSink) (AccountMap, map[string]bool, error) {
|
||||
diffPathsAtB := make(map[string]bool)
|
||||
diffAcountsAtB := make(AccountMap)
|
||||
it, _ := trie.NewDifferenceIterator(iters.older, iters.newer)
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
// created vs updated is important for leaf nodes since we need to diff their storage
|
||||
// so we need to map all changed accounts at B to their leafkey, since account can change paths but not leafkey
|
||||
var account types.StateAccount
|
||||
if err := rlp.DecodeBytes(nodeElements[1].([]byte), &account); err != nil {
|
||||
return nil, nil, fmt.Errorf("error decoding account for leaf node at path %x nerror: %v", node.Path, err)
|
||||
}
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
diffAcountsAtB[common.Bytes2Hex(leafKey)] = accountWrapper{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
LeafKey: leafKey,
|
||||
Account: &account,
|
||||
}
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
// create a diff for any intermediate node that has changed at b
|
||||
// created vs updated makes no difference for intermediate nodes since we do not need to diff storage
|
||||
if err := output(sdtypes.StateNode{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
// add both intermediate and leaf node paths to the list of diffPathsAtB
|
||||
diffPathsAtB[common.Bytes2Hex(node.Path)] = true
|
||||
}
|
||||
return diffAcountsAtB, diffPathsAtB, it.Error()
|
||||
}
|
||||
|
||||
// deletedOrUpdatedState returns a slice of all the paths that are emptied at B
|
||||
// and a mapping of their leafkeys to all the accounts that exist in a different state at A than B
|
||||
func (sdb *builder) deletedOrUpdatedState(iters iterPair, diffPathsAtB map[string]bool, output sdtypes.StateNodeSink) (AccountMap, error) {
|
||||
diffAccountAtA := make(AccountMap)
|
||||
it, _ := trie.NewDifferenceIterator(iters.newer, iters.older)
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
// map all different accounts at A to their leafkey
|
||||
var account types.StateAccount
|
||||
if err := rlp.DecodeBytes(nodeElements[1].([]byte), &account); err != nil {
|
||||
return nil, fmt.Errorf("error decoding account for leaf node at path %x nerror: %v", node.Path, err)
|
||||
}
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
diffAccountAtA[common.Bytes2Hex(leafKey)] = accountWrapper{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
LeafKey: leafKey,
|
||||
Account: &account,
|
||||
}
|
||||
// if this node's path did not show up in diffPathsAtB
|
||||
// that means the node at this path was deleted (or moved) in B
|
||||
// emit an empty "removed" diff to signify as such
|
||||
if _, ok := diffPathsAtB[common.Bytes2Hex(node.Path)]; !ok {
|
||||
if err := output(sdtypes.StateNode{
|
||||
Path: node.Path,
|
||||
NodeValue: []byte{},
|
||||
NodeType: sdtypes.Removed,
|
||||
LeafKey: leafKey,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
// if this node's path did not show up in diffPathsAtB
|
||||
// that means the node at this path was deleted (or moved) in B
|
||||
// emit an empty "removed" diff to signify as such
|
||||
if _, ok := diffPathsAtB[common.Bytes2Hex(node.Path)]; !ok {
|
||||
if err := output(sdtypes.StateNode{
|
||||
Path: node.Path,
|
||||
NodeValue: []byte{},
|
||||
NodeType: sdtypes.Removed,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// fall through, we did everything we need to do with these node types
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
}
|
||||
return diffAccountAtA, it.Error()
|
||||
}
|
||||
|
||||
// buildAccountUpdates uses the account diffs maps for A => B and B => A and the known intersection of their leafkeys
|
||||
// to generate the statediff node objects for all of the accounts that existed at both A and B but in different states
|
||||
// needs to be called before building account creations and deletions as this mutates
|
||||
// those account maps to remove the accounts which were updated
|
||||
func (sdb *builder) buildAccountUpdates(creations, deletions AccountMap, updatedKeys []string, watchedStorageKeys []common.Hash, intermediateStorageNodes bool, output sdtypes.StateNodeSink) error {
|
||||
var err error
|
||||
for _, key := range updatedKeys {
|
||||
createdAcc := creations[key]
|
||||
deletedAcc := deletions[key]
|
||||
var storageDiffs []sdtypes.StorageNode
|
||||
if deletedAcc.Account != nil && createdAcc.Account != nil {
|
||||
oldSR := deletedAcc.Account.Root
|
||||
newSR := createdAcc.Account.Root
|
||||
err = sdb.buildStorageNodesIncremental(oldSR, newSR, watchedStorageKeys, intermediateStorageNodes, storageNodeAppender(&storageDiffs))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed building incremental storage diffs for account with leafkey %s\r\nerror: %v", key, err)
|
||||
}
|
||||
}
|
||||
if err = output(sdtypes.StateNode{
|
||||
NodeType: createdAcc.NodeType,
|
||||
Path: createdAcc.Path,
|
||||
NodeValue: createdAcc.NodeValue,
|
||||
LeafKey: createdAcc.LeafKey,
|
||||
StorageNodes: storageDiffs,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(creations, key)
|
||||
delete(deletions, key)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildAccountCreations returns the statediff node objects for all the accounts that exist at B but not at A
|
||||
// it also returns the code and codehash for created contract accounts
|
||||
func (sdb *builder) buildAccountCreations(accounts AccountMap, watchedStorageKeys []common.Hash, intermediateStorageNodes bool, output sdtypes.StateNodeSink, codeOutput sdtypes.CodeSink) error {
|
||||
for _, val := range accounts {
|
||||
diff := sdtypes.StateNode{
|
||||
NodeType: val.NodeType,
|
||||
Path: val.Path,
|
||||
LeafKey: val.LeafKey,
|
||||
NodeValue: val.NodeValue,
|
||||
}
|
||||
if !bytes.Equal(val.Account.CodeHash, nullCodeHash) {
|
||||
// For contract creations, any storage node contained is a diff
|
||||
var storageDiffs []sdtypes.StorageNode
|
||||
err := sdb.buildStorageNodesEventual(val.Account.Root, watchedStorageKeys, intermediateStorageNodes, storageNodeAppender(&storageDiffs))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed building eventual storage diffs for node %x\r\nerror: %v", val.Path, err)
|
||||
}
|
||||
diff.StorageNodes = storageDiffs
|
||||
// emit codehash => code mappings for code
|
||||
codeHash := common.BytesToHash(val.Account.CodeHash)
|
||||
code, err := sdb.stateCache.ContractCode(common.Hash{}, codeHash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve code for codehash %s\r\n error: %v", codeHash.String(), err)
|
||||
}
|
||||
if err := codeOutput(sdtypes.CodeAndCodeHash{
|
||||
Hash: codeHash,
|
||||
Code: code,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := output(diff); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildStorageNodesEventual builds the storage diff node objects for a created account
|
||||
// i.e. it returns all the storage nodes at this state, since there is no previous state
|
||||
func (sdb *builder) buildStorageNodesEventual(sr common.Hash, watchedStorageKeys []common.Hash, intermediateNodes bool, output sdtypes.StorageNodeSink) error {
|
||||
if bytes.Equal(sr.Bytes(), emptyContractRoot.Bytes()) {
|
||||
return nil
|
||||
}
|
||||
log.Debug("Storage Root For Eventual Diff", "root", sr.Hex())
|
||||
sTrie, err := sdb.stateCache.OpenTrie(sr)
|
||||
if err != nil {
|
||||
log.Info("error in build storage diff eventual", "error", err)
|
||||
return err
|
||||
}
|
||||
it := sTrie.NodeIterator(make([]byte, 0))
|
||||
err = sdb.buildStorageNodesFromTrie(it, watchedStorageKeys, intermediateNodes, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildStorageNodesFromTrie returns all the storage diff node objects in the provided node iterator
|
||||
// if any storage keys are provided it will only return those leaf nodes
|
||||
// including intermediate nodes can be turned on or off
|
||||
func (sdb *builder) buildStorageNodesFromTrie(it trie.NodeIterator, watchedStorageKeys []common.Hash, intermediateNodes bool, output sdtypes.StorageNodeSink) error {
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
if isWatchedStorageKey(watchedStorageKeys, leafKey) {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
LeafKey: leafKey,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
if intermediateNodes {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
}
|
||||
return it.Error()
|
||||
}
|
||||
|
||||
// buildStorageNodesIncremental builds the storage diff node objects for all nodes that exist in a different state at B than A
|
||||
func (sdb *builder) buildStorageNodesIncremental(oldSR common.Hash, newSR common.Hash, watchedStorageKeys []common.Hash, intermediateNodes bool, output sdtypes.StorageNodeSink) error {
|
||||
if bytes.Equal(newSR.Bytes(), oldSR.Bytes()) {
|
||||
return nil
|
||||
}
|
||||
log.Debug("Storage Roots for Incremental Diff", "old", oldSR.Hex(), "new", newSR.Hex())
|
||||
oldTrie, err := sdb.stateCache.OpenTrie(oldSR)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newTrie, err := sdb.stateCache.OpenTrie(newSR)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
diffPathsAtB, err := sdb.createdAndUpdatedStorage(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}), watchedStorageKeys, intermediateNodes, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = sdb.deletedOrUpdatedStorage(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}), diffPathsAtB, watchedStorageKeys, intermediateNodes, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sdb *builder) createdAndUpdatedStorage(a, b trie.NodeIterator, watchedKeys []common.Hash, intermediateNodes bool, output sdtypes.StorageNodeSink) (map[string]bool, error) {
|
||||
diffPathsAtB := make(map[string]bool)
|
||||
it, _ := trie.NewDifferenceIterator(a, b)
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
if isWatchedStorageKey(watchedKeys, leafKey) {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
LeafKey: leafKey,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
if intermediateNodes {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: node.NodeType,
|
||||
Path: node.Path,
|
||||
NodeValue: node.NodeValue,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
diffPathsAtB[common.Bytes2Hex(node.Path)] = true
|
||||
}
|
||||
return diffPathsAtB, it.Error()
|
||||
}
|
||||
|
||||
func (sdb *builder) deletedOrUpdatedStorage(a, b trie.NodeIterator, diffPathsAtB map[string]bool, watchedKeys []common.Hash, intermediateNodes bool, output sdtypes.StorageNodeSink) error {
|
||||
it, _ := trie.NewDifferenceIterator(b, a)
|
||||
for it.Next(true) {
|
||||
if it.Leaf() || bytes.Equal(nullHashBytes, it.Hash().Bytes()) {
|
||||
continue
|
||||
}
|
||||
node, nodeElements, err := resolveNode(it, sdb.stateCache.TrieDB())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// if this node path showed up in diffPathsAtB
|
||||
// that means this node was updated at B and we already have the updated diff for it
|
||||
// otherwise that means this node was deleted in B and we need to add a "removed" diff to represent that event
|
||||
if _, ok := diffPathsAtB[common.Bytes2Hex(node.Path)]; ok {
|
||||
continue
|
||||
}
|
||||
switch node.NodeType {
|
||||
case sdtypes.Leaf:
|
||||
partialPath := trie.CompactToHex(nodeElements[0].([]byte))
|
||||
valueNodePath := append(node.Path, partialPath...)
|
||||
encodedPath := trie.HexToCompact(valueNodePath)
|
||||
leafKey := encodedPath[1:]
|
||||
if isWatchedStorageKey(watchedKeys, leafKey) {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: sdtypes.Removed,
|
||||
Path: node.Path,
|
||||
NodeValue: []byte{},
|
||||
LeafKey: leafKey,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case sdtypes.Extension, sdtypes.Branch:
|
||||
if intermediateNodes {
|
||||
if err := output(sdtypes.StorageNode{
|
||||
NodeType: sdtypes.Removed,
|
||||
Path: node.Path,
|
||||
NodeValue: []byte{},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected node type %s", node.NodeType)
|
||||
}
|
||||
}
|
||||
return it.Error()
|
||||
}
|
||||
|
||||
// isWatchedAddress is used to check if a state account corresponds to one of the addresses the builder is configured to watch
|
||||
func isWatchedAddress(watchedAddresses []common.Address, stateLeafKey []byte) bool {
|
||||
// If we aren't watching any specific addresses, we are watching everything
|
||||
if len(watchedAddresses) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, addr := range watchedAddresses {
|
||||
addrHashKey := crypto.Keccak256(addr.Bytes())
|
||||
if bytes.Equal(addrHashKey, stateLeafKey) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isWatchedStorageKey is used to check if a storage leaf corresponds to one of the storage slots the builder is configured to watch
|
||||
func isWatchedStorageKey(watchedKeys []common.Hash, storageLeafKey []byte) bool {
|
||||
// If we aren't watching any specific addresses, we are watching everything
|
||||
if len(watchedKeys) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, hashKey := range watchedKeys {
|
||||
if bytes.Equal(hashKey.Bytes(), storageLeafKey) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
-2331
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,9 @@
|
||||
package statediff
|
||||
|
||||
// ServiceConfig holds config params for the statediffing service
|
||||
type ServiceConfig struct {
|
||||
ServiceWorkers uint
|
||||
TrieWorkers uint
|
||||
WorkerQueueSize uint
|
||||
PreRuns []RangeRequest
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Contains a batch of utility type declarations used by the tests. As the node
|
||||
// operates on unique types, a lot of them are needed to check various features.
|
||||
|
||||
package statediff
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func sortKeys(data AccountMap) []string {
|
||||
keys := make([]string, 0, len(data))
|
||||
for key := range data {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// findIntersection finds the set of strings from both arrays that are equivalent
|
||||
// a and b must first be sorted
|
||||
// this is used to find which keys have been both "deleted" and "created" i.e. they were updated
|
||||
func findIntersection(a, b []string) []string {
|
||||
lenA := len(a)
|
||||
lenB := len(b)
|
||||
iOfA, iOfB := 0, 0
|
||||
updates := make([]string, 0)
|
||||
if iOfA >= lenA || iOfB >= lenB {
|
||||
return updates
|
||||
}
|
||||
for {
|
||||
switch strings.Compare(a[iOfA], b[iOfB]) {
|
||||
// -1 when a[iOfA] < b[iOfB]
|
||||
case -1:
|
||||
iOfA++
|
||||
if iOfA >= lenA {
|
||||
return updates
|
||||
}
|
||||
// 0 when a[iOfA] == b[iOfB]
|
||||
case 0:
|
||||
updates = append(updates, a[iOfA])
|
||||
iOfA++
|
||||
iOfB++
|
||||
if iOfA >= lenA || iOfB >= lenB {
|
||||
return updates
|
||||
}
|
||||
// 1 when a[iOfA] > b[iOfB]
|
||||
case 1:
|
||||
iOfB++
|
||||
if iOfB >= lenB {
|
||||
return updates
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2021 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package prom
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
dbmetrics "github.com/cerc-io/plugeth-statediff/indexer/database/metrics"
|
||||
)
|
||||
|
||||
const (
|
||||
namespace = "eth_statediff_service"
|
||||
subsystem = "connections"
|
||||
)
|
||||
|
||||
// DBStatsGetter is an interface that gets sql.DBStats.
|
||||
type DBStatsGetter interface {
|
||||
Stats() dbmetrics.DbStats
|
||||
}
|
||||
|
||||
// DBStatsCollector implements the prometheus.Collector interface.
|
||||
type DBStatsCollector struct {
|
||||
sg DBStatsGetter
|
||||
|
||||
// descriptions of exported metrics
|
||||
maxOpenDesc *prometheus.Desc
|
||||
openDesc *prometheus.Desc
|
||||
inUseDesc *prometheus.Desc
|
||||
idleDesc *prometheus.Desc
|
||||
waitedForDesc *prometheus.Desc
|
||||
blockedSecondsDesc *prometheus.Desc
|
||||
closedMaxIdleDesc *prometheus.Desc
|
||||
closedMaxLifetimeDesc *prometheus.Desc
|
||||
}
|
||||
|
||||
// NewDBStatsCollector creates a new DBStatsCollector.
|
||||
func NewDBStatsCollector(dbName string, sg DBStatsGetter) *DBStatsCollector {
|
||||
labels := prometheus.Labels{"db_name": dbName}
|
||||
return &DBStatsCollector{
|
||||
sg: sg,
|
||||
maxOpenDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "max_open"),
|
||||
"Maximum number of open connections to the database.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
openDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "open"),
|
||||
"The number of established connections both in use and idle.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
inUseDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "in_use"),
|
||||
"The number of connections currently in use.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
idleDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "idle"),
|
||||
"The number of idle connections.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
waitedForDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "waited_for"),
|
||||
"The total number of connections waited for.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
blockedSecondsDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "blocked_seconds"),
|
||||
"The total time blocked waiting for a new connection.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
closedMaxIdleDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "closed_max_idle"),
|
||||
"The total number of connections closed due to SetMaxIdleConns.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
closedMaxLifetimeDesc: prometheus.NewDesc(
|
||||
prometheus.BuildFQName(namespace, subsystem, "closed_max_lifetime"),
|
||||
"The total number of connections closed due to SetConnMaxLifetime.",
|
||||
nil,
|
||||
labels,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Describe implements the prometheus.Collector interface.
|
||||
func (c DBStatsCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||
ch <- c.maxOpenDesc
|
||||
ch <- c.openDesc
|
||||
ch <- c.inUseDesc
|
||||
ch <- c.idleDesc
|
||||
ch <- c.waitedForDesc
|
||||
ch <- c.blockedSecondsDesc
|
||||
ch <- c.closedMaxIdleDesc
|
||||
ch <- c.closedMaxLifetimeDesc
|
||||
}
|
||||
|
||||
// Collect implements the prometheus.Collector interface.
|
||||
func (c DBStatsCollector) Collect(ch chan<- prometheus.Metric) {
|
||||
stats := c.sg.Stats()
|
||||
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.maxOpenDesc,
|
||||
prometheus.GaugeValue,
|
||||
float64(stats.MaxOpen()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.openDesc,
|
||||
prometheus.GaugeValue,
|
||||
float64(stats.Open()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.inUseDesc,
|
||||
prometheus.GaugeValue,
|
||||
float64(stats.InUse()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.idleDesc,
|
||||
prometheus.GaugeValue,
|
||||
float64(stats.Idle()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.waitedForDesc,
|
||||
prometheus.CounterValue,
|
||||
float64(stats.WaitCount()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.blockedSecondsDesc,
|
||||
prometheus.CounterValue,
|
||||
stats.WaitDuration().Seconds(),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.closedMaxIdleDesc,
|
||||
prometheus.CounterValue,
|
||||
float64(stats.MaxIdleClosed()),
|
||||
)
|
||||
ch <- prometheus.MustNewConstMetric(
|
||||
c.closedMaxLifetimeDesc,
|
||||
prometheus.CounterValue,
|
||||
float64(stats.MaxLifetimeClosed()),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2020 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package prom
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
)
|
||||
|
||||
// HTTPMiddleware http connection metric reader
|
||||
func HTTPMiddleware(next http.Handler) http.Handler {
|
||||
if !metrics {
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
httpCount.Inc()
|
||||
|
||||
start := time.Now()
|
||||
next.ServeHTTP(w, r)
|
||||
duration := time.Now().Sub(start)
|
||||
httpDuration.Observe(float64(duration.Seconds()))
|
||||
})
|
||||
}
|
||||
|
||||
// IPCMiddleware unix-socket connection counter
|
||||
func IPCMiddleware(server *rpc.Server, client rpc.Conn) {
|
||||
if metrics {
|
||||
ipcCount.Inc()
|
||||
}
|
||||
server.ServeCodec(rpc.NewCodec(client), 0)
|
||||
if metrics {
|
||||
ipcCount.Dec()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2021 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package prom
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
const (
|
||||
statsSubsystem = "stats"
|
||||
subsystemHTTP = "http"
|
||||
subsystemIPC = "ipc"
|
||||
)
|
||||
|
||||
var (
|
||||
metrics bool
|
||||
|
||||
queuedRanges prometheus.Gauge
|
||||
lastLoadedHeight prometheus.Gauge
|
||||
lastProcessedHeight prometheus.Gauge
|
||||
|
||||
tBlockLoad prometheus.Histogram
|
||||
tBlockProcessing prometheus.Histogram
|
||||
tStateProcessing prometheus.Histogram
|
||||
tTxCommit prometheus.Histogram
|
||||
|
||||
httpCount prometheus.Counter
|
||||
httpDuration prometheus.Histogram
|
||||
ipcCount prometheus.Gauge
|
||||
)
|
||||
|
||||
const (
|
||||
RANGES_QUEUED = "ranges_queued"
|
||||
LOADED_HEIGHT = "loaded_height"
|
||||
PROCESSED_HEIGHT = "processed_height"
|
||||
T_BLOCK_LOAD = "t_block_load"
|
||||
T_BLOCK_PROCESSING = "t_block_processing"
|
||||
T_STATE_PROCESSING = "t_state_processing"
|
||||
T_POSTGRES_TX_COMMIT = "t_postgres_tx_commit"
|
||||
)
|
||||
|
||||
// Init module initialization
|
||||
func Init() {
|
||||
metrics = true
|
||||
|
||||
queuedRanges = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Name: RANGES_QUEUED,
|
||||
Help: "Number of range requests currently queued",
|
||||
})
|
||||
lastLoadedHeight = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Name: LOADED_HEIGHT,
|
||||
Help: "The last block that was loaded for processing",
|
||||
})
|
||||
lastProcessedHeight = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Name: PROCESSED_HEIGHT,
|
||||
Help: "The last block that was processed",
|
||||
})
|
||||
|
||||
tBlockLoad = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: statsSubsystem,
|
||||
Name: T_BLOCK_LOAD,
|
||||
Help: "Block loading time",
|
||||
})
|
||||
tBlockProcessing = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: statsSubsystem,
|
||||
Name: T_BLOCK_PROCESSING,
|
||||
Help: "Block (header, uncles, txs, rcts, tx trie, rct trie) processing time",
|
||||
})
|
||||
tStateProcessing = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: statsSubsystem,
|
||||
Name: T_STATE_PROCESSING,
|
||||
Help: "State (state trie, storage tries, and code) processing time",
|
||||
})
|
||||
tTxCommit = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: statsSubsystem,
|
||||
Name: T_POSTGRES_TX_COMMIT,
|
||||
Help: "Postgres tx commit time",
|
||||
})
|
||||
|
||||
httpCount = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: subsystemHTTP,
|
||||
Name: "count",
|
||||
Help: "http request count",
|
||||
})
|
||||
httpDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: subsystemHTTP,
|
||||
Name: "duration",
|
||||
Help: "http request duration",
|
||||
})
|
||||
ipcCount = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: subsystemIPC,
|
||||
Name: "count",
|
||||
Help: "unix socket connection count",
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterDBCollector create metric collector for given connection
|
||||
func RegisterDBCollector(name string, db DBStatsGetter) {
|
||||
if metrics {
|
||||
prometheus.Register(NewDBStatsCollector(name, db))
|
||||
}
|
||||
}
|
||||
|
||||
// IncQueuedRanges increments the number of queued range requests
|
||||
func IncQueuedRanges() {
|
||||
if metrics {
|
||||
queuedRanges.Inc()
|
||||
}
|
||||
}
|
||||
|
||||
// DecQueuedRanges decrements the number of queued range requests
|
||||
func DecQueuedRanges() {
|
||||
if metrics {
|
||||
queuedRanges.Dec()
|
||||
}
|
||||
}
|
||||
|
||||
// SetLastLoadedHeight sets last loaded height
|
||||
func SetLastLoadedHeight(height int64) {
|
||||
if metrics {
|
||||
lastLoadedHeight.Set(float64(height))
|
||||
}
|
||||
}
|
||||
|
||||
// SetLastProcessedHeight sets last processed height
|
||||
func SetLastProcessedHeight(height int64) {
|
||||
if metrics {
|
||||
lastProcessedHeight.Set(float64(height))
|
||||
}
|
||||
}
|
||||
|
||||
// SetTimeMetric time metric observation
|
||||
func SetTimeMetric(name string, t time.Duration) {
|
||||
if !metrics {
|
||||
return
|
||||
}
|
||||
tAsF64 := t.Seconds()
|
||||
switch name {
|
||||
case T_BLOCK_LOAD:
|
||||
tBlockLoad.Observe(tAsF64)
|
||||
case T_BLOCK_PROCESSING:
|
||||
tBlockProcessing.Observe(tAsF64)
|
||||
case T_STATE_PROCESSING:
|
||||
tStateProcessing.Observe(tAsF64)
|
||||
case T_POSTGRES_TX_COMMIT:
|
||||
tTxCommit.Observe(tAsF64)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2021 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package prom
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Listen start listening http
|
||||
func Listen(addr string) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
srv := http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
}
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil {
|
||||
logrus.Fatal(err)
|
||||
}
|
||||
}()
|
||||
return &srv
|
||||
}
|
||||
+60
-28
@@ -16,6 +16,7 @@
|
||||
package statediff
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
@@ -25,31 +26,49 @@ import (
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/ethdb"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
"github.com/ethereum/go-ethereum/triedb"
|
||||
)
|
||||
|
||||
// LvlDBReader exposes the necessary read functions on lvldb
|
||||
type LvlDBReader struct {
|
||||
// Reader interface required by the statediffing service
|
||||
type Reader interface {
|
||||
GetBlockByHash(hash common.Hash) (*types.Block, error)
|
||||
GetBlockByNumber(number uint64) (*types.Block, error)
|
||||
GetReceiptsByHash(hash common.Hash) (types.Receipts, error)
|
||||
GetTdByHash(hash common.Hash) (*big.Int, error)
|
||||
StateDB() state.Database
|
||||
GetLatestHeader() (*types.Header, error)
|
||||
}
|
||||
|
||||
// EthDBReader exposes the necessary Reader methods on an ethdb
|
||||
type EthDBReader struct {
|
||||
ethDB ethdb.Database
|
||||
stateDB state.Database
|
||||
chainConfig *params.ChainConfig
|
||||
}
|
||||
|
||||
// ReaderConfig struct for initializing a LvlDBReader
|
||||
type ReaderConfig struct {
|
||||
TrieConfig *trie.Config
|
||||
ChainConfig *params.ChainConfig
|
||||
Path, AncientPath string
|
||||
DBCacheSize int
|
||||
type EthDBReaderConfig struct {
|
||||
TrieConfig *triedb.Config
|
||||
ChainConfig *params.ChainConfig
|
||||
Path, AncientPath, Url string
|
||||
DBCacheSize int
|
||||
}
|
||||
|
||||
// NewLvlDBReader creates a new LvlDBReader
|
||||
func NewLvlDBReader(conf ReaderConfig) (*LvlDBReader, error) {
|
||||
edb, err := rawdb.NewLevelDBDatabaseWithFreezer(conf.Path, conf.DBCacheSize, 256, conf.AncientPath, "eth-statediff-service", true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// NewEthDBReader creates a new Reader using LevelDB
|
||||
func NewEthDBReader(conf EthDBReaderConfig) (*EthDBReader, error) {
|
||||
opts := rawdb.OpenOptions{
|
||||
Directory: conf.Path,
|
||||
AncientsDirectory: conf.AncientPath,
|
||||
Namespace: "eth-statediff-service",
|
||||
Cache: conf.DBCacheSize,
|
||||
Handles: 256,
|
||||
ReadOnly: true,
|
||||
}
|
||||
return &LvlDBReader{
|
||||
edb, err := rawdb.Open(opts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open DB: %w", err)
|
||||
}
|
||||
|
||||
return &EthDBReader{
|
||||
ethDB: edb,
|
||||
stateDB: state.NewDatabaseWithConfig(edb, conf.TrieConfig),
|
||||
chainConfig: conf.ChainConfig,
|
||||
@@ -57,54 +76,67 @@ func NewLvlDBReader(conf ReaderConfig) (*LvlDBReader, error) {
|
||||
}
|
||||
|
||||
// GetBlockByHash gets block by hash
|
||||
func (ldr *LvlDBReader) GetBlockByHash(hash common.Hash) (*types.Block, error) {
|
||||
func (ldr *EthDBReader) GetBlockByHash(hash common.Hash) (*types.Block, error) {
|
||||
height := rawdb.ReadHeaderNumber(ldr.ethDB, hash)
|
||||
if height == nil {
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash.String())
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash)
|
||||
}
|
||||
block := rawdb.ReadBlock(ldr.ethDB, hash, *height)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("unable to read block at height %d hash %s", *height, hash.String())
|
||||
return nil, fmt.Errorf("unable to read block at height %d hash %s", *height, hash)
|
||||
}
|
||||
return block, nil
|
||||
}
|
||||
|
||||
func (ldr *LvlDBReader) GetBlockByNumber(number uint64) (*types.Block, error) {
|
||||
func (ldr *EthDBReader) GetBlockByNumber(number uint64) (*types.Block, error) {
|
||||
hash := rawdb.ReadCanonicalHash(ldr.ethDB, number)
|
||||
block := rawdb.ReadBlock(ldr.ethDB, hash, number)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("unable to read block at height %d hash %s", number, hash.String())
|
||||
return nil, fmt.Errorf("unable to read block at height %d hash %s", number, hash)
|
||||
}
|
||||
return block, nil
|
||||
}
|
||||
|
||||
// GetReceiptsByHash gets receipt by hash
|
||||
func (ldr *LvlDBReader) GetReceiptsByHash(hash common.Hash) (types.Receipts, error) {
|
||||
func (ldr *EthDBReader) GetReceiptsByHash(hash common.Hash) (types.Receipts, error) {
|
||||
number := rawdb.ReadHeaderNumber(ldr.ethDB, hash)
|
||||
if number == nil {
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash.String())
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash)
|
||||
}
|
||||
receipts := rawdb.ReadReceipts(ldr.ethDB, hash, *number, ldr.chainConfig)
|
||||
header := rawdb.ReadHeader(ldr.ethDB, hash, *number)
|
||||
if header == nil {
|
||||
return nil, fmt.Errorf("unable to read header for header hash %s", hash)
|
||||
}
|
||||
receipts := rawdb.ReadReceipts(ldr.ethDB, hash, *number, header.Time, ldr.chainConfig)
|
||||
if receipts == nil {
|
||||
return nil, fmt.Errorf("unable to read receipts at height %d hash %s", number, hash.String())
|
||||
return nil, fmt.Errorf("unable to read receipts at height %d hash %s", number, hash)
|
||||
}
|
||||
return receipts, nil
|
||||
}
|
||||
|
||||
// GetTdByHash gets td by hash
|
||||
func (ldr *LvlDBReader) GetTdByHash(hash common.Hash) (*big.Int, error) {
|
||||
func (ldr *EthDBReader) GetTdByHash(hash common.Hash) (*big.Int, error) {
|
||||
number := rawdb.ReadHeaderNumber(ldr.ethDB, hash)
|
||||
if number == nil {
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash.String())
|
||||
return nil, fmt.Errorf("unable to read header height for header hash %s", hash)
|
||||
}
|
||||
td := rawdb.ReadTd(ldr.ethDB, hash, *number)
|
||||
if td == nil {
|
||||
return nil, fmt.Errorf("unable to read total difficulty at height %d hash %s", number, hash.String())
|
||||
return nil, fmt.Errorf("unable to read total difficulty at height %d hash %s", number, hash)
|
||||
}
|
||||
return td, nil
|
||||
}
|
||||
|
||||
// StateDB returns the underlying statedb
|
||||
func (ldr *LvlDBReader) StateDB() state.Database {
|
||||
func (ldr *EthDBReader) StateDB() state.Database {
|
||||
return ldr.stateDB
|
||||
}
|
||||
|
||||
// GetLatestHeader gets the latest header from the levelDB
|
||||
func (ldr *EthDBReader) GetLatestHeader() (*types.Header, error) {
|
||||
header := rawdb.ReadHeadHeader(ldr.ethDB)
|
||||
if header == nil {
|
||||
return nil, errors.New("unable to read head header")
|
||||
}
|
||||
return header, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2020 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/ethereum/go-ethereum/cmd/utils"
|
||||
"github.com/ethereum/go-ethereum/node"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/cerc-io/eth-statediff-service/pkg/prom"
|
||||
)
|
||||
|
||||
// StartHTTPEndpoint starts the HTTP RPC endpoint, configured with cors/vhosts/modules.
|
||||
func StartHTTPEndpoint(endpoint string, apis []rpc.API, modules []string, cors []string, vhosts []string, timeouts rpc.HTTPTimeouts) (*rpc.Server, error) {
|
||||
|
||||
srv := rpc.NewServer()
|
||||
err := node.RegisterApis(apis, modules, srv)
|
||||
if err != nil {
|
||||
utils.Fatalf("Could not register HTTP API: %w", err)
|
||||
}
|
||||
handler := node.NewHTTPHandlerStack(srv, cors, vhosts, nil)
|
||||
|
||||
// start http server
|
||||
_, addr, err := node.StartHTTPEndpoint(endpoint, rpc.DefaultHTTPTimeouts, prom.HTTPMiddleware(handler))
|
||||
if err != nil {
|
||||
utils.Fatalf("Could not start RPC api: %v", err)
|
||||
}
|
||||
extapiURL := fmt.Sprintf("http://%v/", addr)
|
||||
log.Infof("HTTP endpoint opened %s", extapiURL)
|
||||
|
||||
return srv, err
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2020 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/ethereum/go-ethereum/p2p/netutil"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/cerc-io/eth-statediff-service/pkg/prom"
|
||||
)
|
||||
|
||||
var (
|
||||
// On Linux, sun_path is 108 bytes in size
|
||||
// see http://man7.org/linux/man-pages/man7/unix.7.html
|
||||
maxPathSize = 108
|
||||
)
|
||||
|
||||
// ipcListen will create a Unix socket on the given endpoint.
|
||||
func ipcListen(endpoint string) (net.Listener, error) {
|
||||
if len(endpoint) > int(maxPathSize) {
|
||||
log.Warn(fmt.Sprintf("The ipc endpoint is longer than %d characters. ", maxPathSize),
|
||||
"endpoint", endpoint)
|
||||
}
|
||||
|
||||
// Ensure the IPC path exists and remove any previous leftover
|
||||
if err := os.MkdirAll(filepath.Dir(endpoint), 0751); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
os.Remove(endpoint)
|
||||
l, err := net.Listen("unix", endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
os.Chmod(endpoint, 0600)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func ipcServe(srv *rpc.Server, listener net.Listener) {
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if netutil.IsTemporaryError(err) {
|
||||
log.WithError(err).Warn("rpc accept error")
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
log.WithError(err).Warn("unknown error")
|
||||
continue
|
||||
}
|
||||
log.WithField("addr", conn.RemoteAddr()).Trace("accepted ipc connection")
|
||||
go prom.IPCMiddleware(srv, conn)
|
||||
}
|
||||
}
|
||||
|
||||
// StartIPCEndpoint starts an IPC endpoint.
|
||||
func StartIPCEndpoint(ipcEndpoint string, apis []rpc.API) (net.Listener, *rpc.Server, error) {
|
||||
// Register all the APIs exposed by the services.
|
||||
handler := rpc.NewServer()
|
||||
for _, api := range apis {
|
||||
if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
log.WithField("namespace", api.Namespace).Debug("IPC server registered")
|
||||
}
|
||||
// All APIs registered, start the IPC listener.
|
||||
listener, err := ipcListen(ipcEndpoint)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
go ipcServe(handler, listener)
|
||||
return listener, handler, nil
|
||||
}
|
||||
+248
-120
@@ -20,75 +20,57 @@ import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/cerc-io/plugeth-statediff"
|
||||
"github.com/cerc-io/plugeth-statediff/adapt"
|
||||
"github.com/cerc-io/plugeth-statediff/indexer/interfaces"
|
||||
sdtypes "github.com/cerc-io/plugeth-statediff/types"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/node"
|
||||
"github.com/ethereum/go-ethereum/p2p"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
sd "github.com/ethereum/go-ethereum/statediff"
|
||||
sdtypes "github.com/ethereum/go-ethereum/statediff/types"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
ind "github.com/ethereum/go-ethereum/statediff/indexer"
|
||||
"github.com/cerc-io/eth-statediff-service/pkg/prom"
|
||||
)
|
||||
|
||||
// lvlDBReader are the db interfaces required by the statediffing service
|
||||
type lvlDBReader interface {
|
||||
GetBlockByHash(hash common.Hash) (*types.Block, error)
|
||||
GetBlockByNumber(number uint64) (*types.Block, error)
|
||||
GetReceiptsByHash(hash common.Hash) (types.Receipts, error)
|
||||
GetTdByHash(hash common.Hash) (*big.Int, error)
|
||||
StateDB() state.Database
|
||||
}
|
||||
|
||||
// IService is the state-diffing service interface
|
||||
type IService interface {
|
||||
// Start() and Stop()
|
||||
node.Lifecycle
|
||||
// For node service registration
|
||||
APIs() []rpc.API
|
||||
Protocols() []p2p.Protocol
|
||||
// Main event loop for processing state diffs
|
||||
Loop(wg *sync.WaitGroup)
|
||||
// Method to get state diff object at specific block
|
||||
StateDiffAt(blockNumber uint64, params sd.Params) (*sd.Payload, error)
|
||||
// Method to get state diff object at specific block
|
||||
StateDiffFor(blockHash common.Hash, params sd.Params) (*sd.Payload, error)
|
||||
// Method to get state trie object at specific block
|
||||
StateTrieAt(blockNumber uint64, params sd.Params) (*sd.Payload, error)
|
||||
// Method to write state diff object directly to DB
|
||||
WriteStateDiffAt(blockNumber uint64, params sd.Params) error
|
||||
// Method to get state trie object at specific block
|
||||
WriteStateDiffFor(blockHash common.Hash, params sd.Params) error
|
||||
}
|
||||
const defaultQueueSize = 1024
|
||||
|
||||
// Service is the underlying struct for the state diffing service
|
||||
type Service struct {
|
||||
// Used to build the state diff objects
|
||||
Builder Builder
|
||||
// Used to read data from leveldb
|
||||
lvlDBReader lvlDBReader
|
||||
builder statediff.Builder
|
||||
// Used to read data from LevelDB
|
||||
reader Reader
|
||||
// Used to signal shutdown of the service
|
||||
QuitChan chan bool
|
||||
quitChan chan struct{}
|
||||
// Interface for publishing statediffs as PG-IPLD objects
|
||||
indexer ind.Indexer
|
||||
indexer interfaces.StateDiffIndexer
|
||||
// range queue
|
||||
queue chan RangeRequest
|
||||
// number of ranges we can work over concurrently
|
||||
workers uint
|
||||
// ranges configured locally
|
||||
preruns []RangeRequest
|
||||
}
|
||||
|
||||
// NewStateDiffService creates a new Service
|
||||
func NewStateDiffService(lvlDBReader lvlDBReader, indexer ind.Indexer, workers uint) (*Service, error) {
|
||||
builder, err := NewBuilder(lvlDBReader.StateDB(), workers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
func NewStateDiffService(reader Reader, indexer interfaces.StateDiffIndexer, conf ServiceConfig) *Service {
|
||||
builder := statediff.NewBuilder(adapt.GethStateView(reader.StateDB()))
|
||||
builder.SetSubtrieWorkers(conf.TrieWorkers)
|
||||
if conf.WorkerQueueSize == 0 {
|
||||
conf.WorkerQueueSize = defaultQueueSize
|
||||
}
|
||||
return &Service{
|
||||
lvlDBReader: lvlDBReader,
|
||||
Builder: builder,
|
||||
QuitChan: make(chan bool),
|
||||
indexer: indexer,
|
||||
}, nil
|
||||
reader: reader,
|
||||
builder: builder,
|
||||
indexer: indexer,
|
||||
workers: conf.ServiceWorkers,
|
||||
queue: make(chan RangeRequest, conf.WorkerQueueSize),
|
||||
preruns: conf.PreRuns,
|
||||
}
|
||||
}
|
||||
|
||||
// Protocols exports the services p2p protocols, this service has none
|
||||
@@ -108,31 +90,153 @@ func (sds *Service) APIs() []rpc.API {
|
||||
}
|
||||
}
|
||||
|
||||
// Loop is an empty service loop for awaiting rpc requests
|
||||
func (sds *Service) Loop(wg *sync.WaitGroup) {
|
||||
wg.Add(1)
|
||||
for {
|
||||
select {
|
||||
case <-sds.QuitChan:
|
||||
logrus.Info("closing the statediff service loop")
|
||||
wg.Done()
|
||||
return
|
||||
func segmentRange(workers, start, stop uint64, params statediff.Params) []RangeRequest {
|
||||
segmentSize := ((stop - start) + 1) / workers
|
||||
remainder := ((stop - start) + 1) % workers
|
||||
numOfSegments := workers
|
||||
if remainder > 0 {
|
||||
numOfSegments++
|
||||
}
|
||||
segments := make([]RangeRequest, numOfSegments)
|
||||
for i := range segments {
|
||||
end := start + segmentSize - 1
|
||||
if end > stop {
|
||||
end = stop
|
||||
}
|
||||
segments[i] = RangeRequest{start, end, params}
|
||||
start = end + 1
|
||||
}
|
||||
return segments
|
||||
}
|
||||
|
||||
// Run does a one-off processing run on the provided RangeRequests + any pre-runs, exiting afterwards
|
||||
func (sds *Service) Run(rngs []RangeRequest, parallel bool) error {
|
||||
for _, preRun := range sds.preruns {
|
||||
// if the rangeSize is smaller than the number of workers
|
||||
// make sure we do synchronous processing to avoid quantization issues
|
||||
rangeSize := (preRun.Stop - preRun.Start) + 1
|
||||
numWorkers := uint64(sds.workers)
|
||||
if rangeSize < numWorkers {
|
||||
parallel = false
|
||||
}
|
||||
if parallel {
|
||||
logrus.Infof("parallel processing prerun range (%d, %d) (%d blocks) divided into %d sized chunks with %d workers", preRun.Start, preRun.Stop,
|
||||
rangeSize, rangeSize/numWorkers, numWorkers)
|
||||
workChan := make(chan RangeRequest)
|
||||
quitChan := make(chan struct{})
|
||||
// spin up numWorkers number of worker goroutines
|
||||
wg := new(sync.WaitGroup)
|
||||
for i := 0; i < int(numWorkers); i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case workerSegment := <-workChan:
|
||||
for j := workerSegment.Start; j <= workerSegment.Stop; j++ {
|
||||
if err := sds.WriteStateDiffAt(j, workerSegment.Params); err != nil {
|
||||
logrus.Errorf("error writing statediff at height %d in range (%d, %d) : %v", id, workerSegment.Start, workerSegment.Stop, err)
|
||||
}
|
||||
}
|
||||
logrus.Infof("prerun worker %d finished processing range (%d, %d)", id, workerSegment.Start, workerSegment.Stop)
|
||||
case <-quitChan:
|
||||
return
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
// break range up into segments
|
||||
segments := segmentRange(numWorkers, preRun.Start, preRun.Stop, preRun.Params)
|
||||
// send the segments to the work channel
|
||||
for _, segment := range segments {
|
||||
workChan <- segment
|
||||
}
|
||||
close(quitChan)
|
||||
wg.Wait()
|
||||
} else {
|
||||
logrus.Infof("sequential processing prerun range (%d, %d)", preRun.Start, preRun.Stop)
|
||||
for i := preRun.Start; i <= preRun.Stop; i++ {
|
||||
if err := sds.WriteStateDiffAt(i, preRun.Params); err != nil {
|
||||
return fmt.Errorf("error writing statediff at height %d in range (%d, %d) : %v", i, preRun.Start, preRun.Stop, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sds.preruns = nil
|
||||
// At present this code is never called so we have not written the parallel version:
|
||||
for _, rng := range rngs {
|
||||
logrus.Infof("processing requested range (%d, %d)", rng.Start, rng.Stop)
|
||||
for i := rng.Start; i <= rng.Stop; i++ {
|
||||
if err := sds.WriteStateDiffAt(i, rng.Params); err != nil {
|
||||
return fmt.Errorf("error writing statediff at height %d in range (%d, %d) : %v", i, rng.Start, rng.Stop, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Loop is an empty service loop for awaiting rpc requests
|
||||
func (sds *Service) Loop(wg *sync.WaitGroup) error {
|
||||
if sds.quitChan != nil {
|
||||
return fmt.Errorf("service loop is already running")
|
||||
}
|
||||
|
||||
sds.quitChan = make(chan struct{})
|
||||
for i := 0; i < int(sds.workers); i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case blockRange := <-sds.queue:
|
||||
log := logrus.WithField("range", blockRange).WithField("worker", id)
|
||||
log.Debug("processing range")
|
||||
prom.DecQueuedRanges()
|
||||
for j := blockRange.Start; j <= blockRange.Stop; j++ {
|
||||
if err := sds.WriteStateDiffAt(j, blockRange.Params); err != nil {
|
||||
log.Errorf("error writing statediff at block %d: %v", j, err)
|
||||
}
|
||||
select {
|
||||
case <-sds.quitChan:
|
||||
log.Infof("closing service worker (last processed block: %d)", j)
|
||||
return
|
||||
default:
|
||||
log.Infof("Finished processing block %d", j)
|
||||
}
|
||||
}
|
||||
log.Debugf("Finished processing range")
|
||||
case <-sds.quitChan:
|
||||
logrus.Debugf("closing the statediff service loop worker %d", id)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
for _, preRun := range sds.preruns {
|
||||
if err := sds.WriteStateDiffsInRange(preRun.Start, preRun.Stop, preRun.Params); err != nil {
|
||||
close(sds.quitChan)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StateDiffAt returns a state diff object payload at the specific blockheight
|
||||
// This operation cannot be performed back past the point of db pruning; it requires an archival node for historical data
|
||||
func (sds *Service) StateDiffAt(blockNumber uint64, params sd.Params) (*sd.Payload, error) {
|
||||
currentBlock, err := sds.lvlDBReader.GetBlockByNumber(blockNumber)
|
||||
func (sds *Service) StateDiffAt(blockNumber uint64, params statediff.Params) (*statediff.Payload, error) {
|
||||
currentBlock, err := sds.reader.GetBlockByNumber(blockNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logrus.Info(fmt.Sprintf("sending state diff at block %d", blockNumber))
|
||||
logrus.Infof("sending state diff at block %d", blockNumber)
|
||||
|
||||
// compute leaf paths of watched addresses in the params
|
||||
params.ComputeWatchedAddressesLeafPaths()
|
||||
|
||||
if blockNumber == 0 {
|
||||
return sds.processStateDiff(currentBlock, common.Hash{}, params)
|
||||
}
|
||||
parentBlock, err := sds.lvlDBReader.GetBlockByHash(currentBlock.ParentHash())
|
||||
parentBlock, err := sds.reader.GetBlockByHash(currentBlock.ParentHash())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -141,16 +245,20 @@ func (sds *Service) StateDiffAt(blockNumber uint64, params sd.Params) (*sd.Paylo
|
||||
|
||||
// StateDiffFor returns a state diff object payload for the specific blockhash
|
||||
// This operation cannot be performed back past the point of db pruning; it requires an archival node for historical data
|
||||
func (sds *Service) StateDiffFor(blockHash common.Hash, params sd.Params) (*sd.Payload, error) {
|
||||
currentBlock, err := sds.lvlDBReader.GetBlockByHash(blockHash)
|
||||
func (sds *Service) StateDiffFor(blockHash common.Hash, params statediff.Params) (*statediff.Payload, error) {
|
||||
currentBlock, err := sds.reader.GetBlockByHash(blockHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logrus.Info(fmt.Sprintf("sending state diff at block %s", blockHash.Hex()))
|
||||
logrus.Infof("sending state diff at block %s", blockHash)
|
||||
|
||||
// compute leaf paths of watched addresses in the params
|
||||
params.ComputeWatchedAddressesLeafPaths()
|
||||
|
||||
if currentBlock.NumberU64() == 0 {
|
||||
return sds.processStateDiff(currentBlock, common.Hash{}, params)
|
||||
}
|
||||
parentBlock, err := sds.lvlDBReader.GetBlockByHash(currentBlock.ParentHash())
|
||||
parentBlock, err := sds.reader.GetBlockByHash(currentBlock.ParentHash())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -158,8 +266,8 @@ func (sds *Service) StateDiffFor(blockHash common.Hash, params sd.Params) (*sd.P
|
||||
}
|
||||
|
||||
// processStateDiff method builds the state diff payload from the current block, parent state root, and provided params
|
||||
func (sds *Service) processStateDiff(currentBlock *types.Block, parentRoot common.Hash, params sd.Params) (*sd.Payload, error) {
|
||||
stateDiff, err := sds.Builder.BuildStateDiffObject(sd.Args{
|
||||
func (sds *Service) processStateDiff(currentBlock *types.Block, parentRoot common.Hash, params statediff.Params) (*statediff.Payload, error) {
|
||||
stateDiff, err := sds.builder.BuildStateDiffObject(statediff.Args{
|
||||
BlockHash: currentBlock.Hash(),
|
||||
BlockNumber: currentBlock.Number(),
|
||||
OldStateRoot: parentRoot,
|
||||
@@ -168,7 +276,7 @@ func (sds *Service) processStateDiff(currentBlock *types.Block, parentRoot commo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stateDiffRlp, err := rlp.EncodeToBytes(stateDiff)
|
||||
stateDiffRlp, err := rlp.EncodeToBytes(&stateDiff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -176,8 +284,8 @@ func (sds *Service) processStateDiff(currentBlock *types.Block, parentRoot commo
|
||||
return sds.newPayload(stateDiffRlp, currentBlock, params)
|
||||
}
|
||||
|
||||
func (sds *Service) newPayload(stateObject []byte, block *types.Block, params sd.Params) (*sd.Payload, error) {
|
||||
payload := &sd.Payload{
|
||||
func (sds *Service) newPayload(stateObject []byte, block *types.Block, params statediff.Params) (*statediff.Payload, error) {
|
||||
payload := &statediff.Payload{
|
||||
StateObjectRlp: stateObject,
|
||||
}
|
||||
if params.IncludeBlock {
|
||||
@@ -189,14 +297,14 @@ func (sds *Service) newPayload(stateObject []byte, block *types.Block, params sd
|
||||
}
|
||||
if params.IncludeTD {
|
||||
var err error
|
||||
payload.TotalDifficulty, err = sds.lvlDBReader.GetTdByHash(block.Hash())
|
||||
payload.TotalDifficulty, err = sds.reader.GetTdByHash(block.Hash())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if params.IncludeReceipts {
|
||||
receiptBuff := new(bytes.Buffer)
|
||||
receipts, err := sds.lvlDBReader.GetReceiptsByHash(block.Hash())
|
||||
receipts, err := sds.reader.GetReceiptsByHash(block.Hash())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -208,116 +316,136 @@ func (sds *Service) newPayload(stateObject []byte, block *types.Block, params sd
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
// StateTrieAt returns a state trie object payload at the specified blockheight
|
||||
// This operation cannot be performed back past the point of db pruning; it requires an archival node for historical data
|
||||
func (sds *Service) StateTrieAt(blockNumber uint64, params sd.Params) (*sd.Payload, error) {
|
||||
currentBlock, err := sds.lvlDBReader.GetBlockByNumber(blockNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logrus.Info(fmt.Sprintf("sending state trie at block %d", blockNumber))
|
||||
return sds.processStateTrie(currentBlock, params)
|
||||
}
|
||||
|
||||
func (sds *Service) processStateTrie(block *types.Block, params sd.Params) (*sd.Payload, error) {
|
||||
stateNodes, err := sds.Builder.BuildStateTrieObject(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stateTrieRlp, err := rlp.EncodeToBytes(stateNodes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logrus.Infof("state trie object at block %d is %d bytes in length", block.Number().Uint64(), len(stateTrieRlp))
|
||||
return sds.newPayload(stateTrieRlp, block, params)
|
||||
}
|
||||
|
||||
// Start is used to begin the service
|
||||
func (sds *Service) Start() error {
|
||||
logrus.Info("starting statediff service")
|
||||
go sds.Loop(new(sync.WaitGroup))
|
||||
return nil
|
||||
return sds.Loop(new(sync.WaitGroup))
|
||||
}
|
||||
|
||||
// Stop is used to close down the service
|
||||
func (sds *Service) Stop() error {
|
||||
logrus.Info("stopping statediff service")
|
||||
close(sds.QuitChan)
|
||||
close(sds.quitChan)
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteStateDiffAt writes a state diff at the specific blockheight directly to the database
|
||||
// This operation cannot be performed back past the point of db pruning; it requires an archival node
|
||||
// for historical data
|
||||
func (sds *Service) WriteStateDiffAt(blockNumber uint64, params sd.Params) error {
|
||||
logrus.Info(fmt.Sprintf("Writing state diff at block %d", blockNumber))
|
||||
currentBlock, err := sds.lvlDBReader.GetBlockByNumber(blockNumber)
|
||||
func (sds *Service) WriteStateDiffAt(blockNumber uint64, params statediff.Params) error {
|
||||
logrus.Infof("Writing state diff at block %d", blockNumber)
|
||||
t := time.Now()
|
||||
currentBlock, err := sds.reader.GetBlockByNumber(blockNumber)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// compute leaf paths of watched addresses in the params
|
||||
params.ComputeWatchedAddressesLeafPaths()
|
||||
|
||||
parentRoot := common.Hash{}
|
||||
if blockNumber != 0 {
|
||||
parentBlock, err := sds.lvlDBReader.GetBlockByHash(currentBlock.ParentHash())
|
||||
parentBlock, err := sds.reader.GetBlockByHash(currentBlock.ParentHash())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parentRoot = parentBlock.Root()
|
||||
}
|
||||
return sds.writeStateDiff(currentBlock, parentRoot, params)
|
||||
return sds.writeStateDiff(currentBlock, parentRoot, params, t)
|
||||
}
|
||||
|
||||
// WriteStateDiffFor writes a state diff for the specific blockHash directly to the database
|
||||
// This operation cannot be performed back past the point of db pruning; it requires an archival node
|
||||
// for historical data
|
||||
func (sds *Service) WriteStateDiffFor(blockHash common.Hash, params sd.Params) error {
|
||||
logrus.Info(fmt.Sprintf("Writing state diff for block %s", blockHash.Hex()))
|
||||
currentBlock, err := sds.lvlDBReader.GetBlockByHash(blockHash)
|
||||
func (sds *Service) WriteStateDiffFor(blockHash common.Hash, params statediff.Params) error {
|
||||
logrus.Infof("Writing state diff for block %s", blockHash)
|
||||
t := time.Now()
|
||||
currentBlock, err := sds.reader.GetBlockByHash(blockHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// compute leaf paths of watched addresses in the params
|
||||
params.ComputeWatchedAddressesLeafPaths()
|
||||
|
||||
parentRoot := common.Hash{}
|
||||
if currentBlock.NumberU64() != 0 {
|
||||
parentBlock, err := sds.lvlDBReader.GetBlockByHash(currentBlock.ParentHash())
|
||||
parentBlock, err := sds.reader.GetBlockByHash(currentBlock.ParentHash())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parentRoot = parentBlock.Root()
|
||||
}
|
||||
return sds.writeStateDiff(currentBlock, parentRoot, params)
|
||||
return sds.writeStateDiff(currentBlock, parentRoot, params, t)
|
||||
}
|
||||
|
||||
// Writes a state diff from the current block, parent state root, and provided params
|
||||
func (sds *Service) writeStateDiff(block *types.Block, parentRoot common.Hash, params sd.Params) error {
|
||||
func (sds *Service) writeStateDiff(block *types.Block, parentRoot common.Hash, params statediff.Params, t time.Time) error {
|
||||
var totalDifficulty *big.Int
|
||||
var receipts types.Receipts
|
||||
var err error
|
||||
if params.IncludeTD {
|
||||
totalDifficulty, err = sds.lvlDBReader.GetTdByHash(block.Hash())
|
||||
totalDifficulty, err = sds.reader.GetTdByHash(block.Hash())
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if params.IncludeReceipts {
|
||||
receipts, err = sds.lvlDBReader.GetReceiptsByHash(block.Hash())
|
||||
receipts, err = sds.reader.GetReceiptsByHash(block.Hash())
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
height := block.Number().Int64()
|
||||
prom.SetLastLoadedHeight(height)
|
||||
prom.SetTimeMetric(prom.T_BLOCK_LOAD, time.Now().Sub(t))
|
||||
t = time.Now()
|
||||
tx, err := sds.indexer.PushBlock(block, receipts, totalDifficulty)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// defer handling of commit/rollback for any return case
|
||||
output := func(node sdtypes.StateNode) error {
|
||||
return sds.indexer.PushStateNode(tx, node)
|
||||
defer tx.RollbackOnFailure(err)
|
||||
|
||||
var nodeMtx, ipldMtx sync.Mutex
|
||||
output := func(node sdtypes.StateLeafNode) error {
|
||||
nodeMtx.Lock()
|
||||
defer nodeMtx.Unlock()
|
||||
return sds.indexer.PushStateNode(tx, node, block.Hash().String())
|
||||
}
|
||||
codeOutput := func(c sdtypes.CodeAndCodeHash) error {
|
||||
return sds.indexer.PushCodeAndCodeHash(tx, c)
|
||||
ipldOutput := func(c sdtypes.IPLD) error {
|
||||
ipldMtx.Lock()
|
||||
defer ipldMtx.Unlock()
|
||||
return sds.indexer.PushIPLD(tx, c)
|
||||
}
|
||||
err = sds.Builder.WriteStateDiffObject(sd.StateRoots{
|
||||
prom.SetTimeMetric(prom.T_BLOCK_PROCESSING, time.Now().Sub(t))
|
||||
t = time.Now()
|
||||
err = sds.builder.WriteStateDiff(statediff.Args{
|
||||
NewStateRoot: block.Root(),
|
||||
OldStateRoot: parentRoot,
|
||||
}, params, output, codeOutput)
|
||||
return tx.Close(err)
|
||||
BlockNumber: block.Number(),
|
||||
BlockHash: block.Hash(),
|
||||
}, params, output, ipldOutput)
|
||||
prom.SetTimeMetric(prom.T_STATE_PROCESSING, time.Now().Sub(t))
|
||||
t = time.Now()
|
||||
err = tx.Submit()
|
||||
prom.SetLastProcessedHeight(height)
|
||||
prom.SetTimeMetric(prom.T_POSTGRES_TX_COMMIT, time.Now().Sub(t))
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteStateDiffsInRange adds a RangeRequest to the work queue
|
||||
func (sds *Service) WriteStateDiffsInRange(start, stop uint64, params statediff.Params) error {
|
||||
if stop < start {
|
||||
return fmt.Errorf("invalid block range (%d, %d): stop height must be greater or equal to start height", start, stop)
|
||||
}
|
||||
blocked := time.NewTimer(30 * time.Second)
|
||||
select {
|
||||
case sds.queue <- RangeRequest{Start: start, Stop: stop, Params: params}:
|
||||
prom.IncQueuedRanges()
|
||||
logrus.Infof("Added range (%d, %d) to the worker queue", start, stop)
|
||||
return nil
|
||||
case <-blocked.C:
|
||||
return fmt.Errorf("unable to add range (%d, %d) to the worker queue", start, stop)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package testhelpers
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/consensus/ethash"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/core/vm"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
)
|
||||
|
||||
// MakeChain creates a chain of n blocks starting at and including parent.
|
||||
// the returned hash chain is ordered head->parent.
|
||||
func MakeChain(n int, parent *types.Block, chainGen func(int, *core.BlockGen)) ([]*types.Block, *core.BlockChain) {
|
||||
config := params.TestChainConfig
|
||||
config.LondonBlock.Set(big.NewInt(10))
|
||||
blocks, _ := core.GenerateChain(config, parent, ethash.NewFaker(), Testdb, n, chainGen)
|
||||
chain, _ := core.NewBlockChain(Testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
|
||||
return blocks, chain
|
||||
}
|
||||
|
||||
func TestSelfDestructChainGen(i int, block *core.BlockGen) {
|
||||
signer := types.HomesteadSigner{}
|
||||
switch i {
|
||||
case 0:
|
||||
// Block 1 is mined by Account1Addr
|
||||
// Account1Addr creates a new contract
|
||||
block.SetCoinbase(TestBankAddress)
|
||||
tx, _ := types.SignTx(types.NewContractCreation(0, big.NewInt(0), 1000000, big.NewInt(0), ContractCode), signer, TestBankKey)
|
||||
ContractAddr = crypto.CreateAddress(TestBankAddress, 0)
|
||||
block.AddTx(tx)
|
||||
case 1:
|
||||
// Block 2 is mined by Account1Addr
|
||||
// Account1Addr self-destructs the contract
|
||||
block.SetCoinbase(TestBankAddress)
|
||||
data := common.Hex2Bytes("43D726D6")
|
||||
tx, _ := types.SignTx(types.NewTransaction(1, ContractAddr, big.NewInt(0), 100000, nil, data), signer, TestBankKey)
|
||||
block.AddTx(tx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChainGen(i int, block *core.BlockGen) {
|
||||
signer := types.HomesteadSigner{}
|
||||
switch i {
|
||||
case 0:
|
||||
// In block 1, the test bank sends account #1 some ether.
|
||||
tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(TestBankAddress), Account1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, TestBankKey)
|
||||
block.AddTx(tx)
|
||||
case 1:
|
||||
// In block 2, the test bank sends some more ether to account #1.
|
||||
// Account1Addr passes it on to account #2.
|
||||
// Account1Addr creates a test contract.
|
||||
tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(TestBankAddress), Account1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, TestBankKey)
|
||||
nonce := block.TxNonce(Account1Addr)
|
||||
tx2, _ := types.SignTx(types.NewTransaction(nonce, Account2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, Account1Key)
|
||||
nonce++
|
||||
tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), 1000000, big.NewInt(0), ContractCode), signer, Account1Key)
|
||||
ContractAddr = crypto.CreateAddress(Account1Addr, nonce)
|
||||
block.AddTx(tx1)
|
||||
block.AddTx(tx2)
|
||||
block.AddTx(tx3)
|
||||
case 2:
|
||||
// Block 3 has a single tx from the bankAccount to the contract, that transfers no value
|
||||
// Block 3 is mined by Account2Addr
|
||||
block.SetCoinbase(Account2Addr)
|
||||
//put function: c16431b9
|
||||
//close function: 43d726d6
|
||||
data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003")
|
||||
tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(TestBankAddress), ContractAddr, big.NewInt(0), 100000, nil, data), signer, TestBankKey)
|
||||
block.AddTx(tx)
|
||||
case 3:
|
||||
// Block 4 has three txs from bankAccount to the contract, that transfer no value
|
||||
// Two set the two original slot positions to 0 and one sets another position to a new value
|
||||
// Block 4 is mined by Account2Addr
|
||||
block.SetCoinbase(Account2Addr)
|
||||
data1 := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
|
||||
data2 := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000")
|
||||
data3 := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000009")
|
||||
|
||||
nonce := block.TxNonce(TestBankAddress)
|
||||
tx1, _ := types.SignTx(types.NewTransaction(nonce, ContractAddr, big.NewInt(0), 100000, nil, data1), signer, TestBankKey)
|
||||
nonce++
|
||||
tx2, _ := types.SignTx(types.NewTransaction(nonce, ContractAddr, big.NewInt(0), 100000, nil, data2), signer, TestBankKey)
|
||||
nonce++
|
||||
tx3, _ := types.SignTx(types.NewTransaction(nonce, ContractAddr, big.NewInt(0), 100000, nil, data3), signer, TestBankKey)
|
||||
block.AddTx(tx1)
|
||||
block.AddTx(tx2)
|
||||
block.AddTx(tx3)
|
||||
case 4:
|
||||
// Block 5 has one tx from bankAccount to the contract, that transfers no value
|
||||
// It sets the remaining storage value to zero
|
||||
// Block 5 is mined by Account1Addr
|
||||
block.SetCoinbase(Account1Addr)
|
||||
data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000")
|
||||
nonce := block.TxNonce(TestBankAddress)
|
||||
tx, _ := types.SignTx(types.NewTransaction(nonce, ContractAddr, big.NewInt(0), 100000, nil, data), signer, TestBankKey)
|
||||
block.AddTx(tx)
|
||||
case 5:
|
||||
// Block 6 has a tx from Account1Key which self-destructs the contract, it transfers no value
|
||||
// Block 6 is mined by Account2Addr
|
||||
block.SetCoinbase(Account2Addr)
|
||||
data := common.Hex2Bytes("43D726D6")
|
||||
tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(Account1Addr), ContractAddr, big.NewInt(0), 100000, nil, data), signer, Account1Key)
|
||||
block.AddTx(tx)
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// Copyright 2019 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package testhelpers
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/rawdb"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
)
|
||||
|
||||
// AddressToLeafKey hashes an returns an address
|
||||
func AddressToLeafKey(address common.Address) []byte {
|
||||
return crypto.Keccak256(address[:])
|
||||
}
|
||||
|
||||
// AddressToEncodedPath hashes an address and appends the even-number leaf flag to it
|
||||
func AddressToEncodedPath(address common.Address) []byte {
|
||||
addrHash := crypto.Keccak256(address[:])
|
||||
decodedPath := append(EvenLeafFlag, addrHash...)
|
||||
return decodedPath
|
||||
}
|
||||
|
||||
// Test variables
|
||||
var (
|
||||
EvenLeafFlag = []byte{byte(2) << 4}
|
||||
NullCodeHash = crypto.Keccak256Hash([]byte{})
|
||||
NullHash = common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000")
|
||||
|
||||
Testdb = rawdb.NewMemoryDatabase()
|
||||
TestBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
|
||||
TestBankAddress = crypto.PubkeyToAddress(TestBankKey.PublicKey) //0x71562b71999873DB5b286dF957af199Ec94617F7
|
||||
BankLeafKey = AddressToLeafKey(TestBankAddress)
|
||||
TestBankFunds = big.NewInt(100000000)
|
||||
Genesis = core.GenesisBlockForTesting(Testdb, TestBankAddress, TestBankFunds)
|
||||
|
||||
Account1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
|
||||
Account2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
|
||||
Account1Addr = crypto.PubkeyToAddress(Account1Key.PublicKey) //0x703c4b2bD70c169f5717101CaeE543299Fc946C7
|
||||
Account2Addr = crypto.PubkeyToAddress(Account2Key.PublicKey) //0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e
|
||||
Account1LeafKey = AddressToLeafKey(Account1Addr)
|
||||
Account2LeafKey = AddressToLeafKey(Account2Addr)
|
||||
ContractCode = common.Hex2Bytes("608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040518060200160405280600160ff16815250600190600161007492919061007a565b506100e4565b82606481019282156100ae579160200282015b828111156100ad578251829060ff1690559160200191906001019061008d565b5b5090506100bb91906100bf565b5090565b6100e191905b808211156100dd5760008160009055506001016100c5565b5090565b90565b6101ca806100f36000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806343d726d61461003b578063c16431b914610045575b600080fd5b61004361007d565b005b61007b6004803603604081101561005b57600080fd5b81019080803590602001909291908035906020019092919050505061015c565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610122576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101746022913960400191505060405180910390fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b806001836064811061016a57fe5b0181905550505056fe4f6e6c79206f776e65722063616e2063616c6c20746869732066756e6374696f6e2ea265627a7a72305820e3747183708fb6bff3f6f7a80fb57dcc1c19f83f9cb25457a3ed5c0424bde66864736f6c634300050a0032")
|
||||
ByteCodeAfterDeployment = common.Hex2Bytes("608060405234801561001057600080fd5b50600436106100365760003560e01c806343d726d61461003b578063c16431b914610045575b600080fd5b61004361007d565b005b61007b6004803603604081101561005b57600080fd5b81019080803590602001909291908035906020019092919050505061015c565b005b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610122576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101746022913960400191505060405180910390fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b806001836064811061016a57fe5b0181905550505056fe4f6e6c79206f776e65722063616e2063616c6c20746869732066756e6374696f6e2ea265627a7a72305820e3747183708fb6bff3f6f7a80fb57dcc1c19f83f9cb25457a3ed5c0424bde66864736f6c634300050a0032")
|
||||
CodeHash = common.HexToHash("0xaaea5efba4fd7b45d7ec03918ac5d8b31aa93b48986af0e6b591f0f087c80127")
|
||||
ContractAddr common.Address
|
||||
|
||||
EmptyRootNode, _ = rlp.EncodeToBytes([]byte{})
|
||||
EmptyContractRoot = crypto.Keccak256Hash(EmptyRootNode)
|
||||
)
|
||||
+10
-11
@@ -20,18 +20,17 @@
|
||||
package statediff
|
||||
|
||||
import (
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
sd "github.com/ethereum/go-ethereum/statediff/types"
|
||||
"fmt"
|
||||
|
||||
sd "github.com/cerc-io/plugeth-statediff"
|
||||
)
|
||||
|
||||
// AccountMap is a mapping of hex encoded path => account wrapper
|
||||
type AccountMap map[string]accountWrapper
|
||||
// RangeRequest holds range quest work params
|
||||
type RangeRequest struct {
|
||||
Start, Stop uint64
|
||||
Params sd.Params
|
||||
}
|
||||
|
||||
// accountWrapper is used to temporary associate the unpacked node with its raw values
|
||||
type accountWrapper struct {
|
||||
Account *types.StateAccount
|
||||
NodeType sd.NodeType
|
||||
Path []byte
|
||||
NodeValue []byte
|
||||
LeafKey []byte
|
||||
func (r RangeRequest) String() string {
|
||||
return fmt.Sprintf("[%d,%d]", r.Start, r.Stop)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Used by the script to count rows (count-lines.sh)
|
||||
COUNT_LINES_LOG=./count-lines.log
|
||||
COUNT_LINES_INPUT_DIR=~/eth-statediff-service/output_dir
|
||||
COUNT_LINES_OUTPUT_FILE=./output-stats.txt
|
||||
|
||||
# Used by the script to dedup output files (dedup.sh)
|
||||
DEDUP_LOG=./dedup.log
|
||||
DEDUP_INPUT_DIR=~/eth-statediff-service/output_dir
|
||||
DEDUP_OUTPUT_DIR=~/eth-statediff-service/dedup_dir
|
||||
DEDUP_SORT_DIR=./.sort
|
||||
|
||||
# Used by the script to perform column checks (check-columns.sh)
|
||||
CHECK_COLUMNS_LOG=./check-columns.log
|
||||
CHECK_COLUMNS_INPUT_DIR=~/eth-statediff-service/output_dir
|
||||
CHECK_COLUMNS_INPUT_DEDUP_DIR=~/eth-statediff-service/dedup_dir
|
||||
CHECK_COLUMNS_OUTPUT_DIR=./check-columns
|
||||
|
||||
# Used by the script to import data (timescaledb-import.sh)
|
||||
IMPORT_LOG=./tsdb-import.log
|
||||
IMPORT_INPUT_DIR=~/eth-statediff-service/output_dir
|
||||
IMPORT_INPUT_DEDUP_DIR=~/eth-statediff-service/dedup_dir
|
||||
TIMESCALEDB_WORKERS=8
|
||||
|
||||
DATABASE_USER=vdbm
|
||||
DATABASE_HOSTNAME=localhost
|
||||
DATABASE_PORT=8077
|
||||
DATABASE_NAME=vulcanize_testing
|
||||
DATABASE_PASSWORD=password
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Requires:
|
||||
# CHECK_COLUMNS_LOG
|
||||
# CHECK_COLUMNS_INPUT_DIR
|
||||
# CHECK_COLUMNS_INPUT_DEDUP_DIR
|
||||
# CHECK_COLUMNS_OUTPUT_DIR
|
||||
|
||||
# env file arg
|
||||
ENV=$1
|
||||
echo "Using env file: ${ENV}"
|
||||
|
||||
# read env file
|
||||
export $(grep -v '^#' ${ENV} | xargs)
|
||||
|
||||
# redirect stdout/stderr to a file
|
||||
exec >"${CHECK_COLUMNS_LOG}" 2>&1
|
||||
|
||||
# create output dir if not exists
|
||||
mkdir -p "${CHECK_COLUMNS_OUTPUT_DIR}"
|
||||
|
||||
start_timestamp=$(date +%s)
|
||||
|
||||
declare -A expected_columns
|
||||
expected_columns=(
|
||||
["public.nodes"]="5"
|
||||
["public.blocks"]="3"
|
||||
# ["eth.access_list_elements"]="?" # skipping as values include ','
|
||||
["eth.log_cids"]="12"
|
||||
["eth.state_accounts"]="7"
|
||||
["eth.storage_cids"]="9"
|
||||
["eth.uncle_cids"]="7"
|
||||
["eth.header_cids"]="16"
|
||||
["eth.receipt_cids"]="10"
|
||||
["eth.state_cids"]="8"
|
||||
["eth.transaction_cids"]="11"
|
||||
)
|
||||
|
||||
for table_name in "${!expected_columns[@]}";
|
||||
do
|
||||
if [ "${table_name}" = "public.blocks" ];
|
||||
then
|
||||
command="$(dirname "$0")/find-bad-rows.sh -i ${CHECK_COLUMNS_INPUT_DEDUP_DIR}/deduped-${table_name}.csv -c ${expected_columns[${table_name}]} -d true -o ${CHECK_COLUMNS_OUTPUT_DIR}/${table_name}.txt"
|
||||
else
|
||||
command="$(dirname "$0")/find-bad-rows.sh -i ${CHECK_COLUMNS_INPUT_DIR}/${table_name}.csv -c ${expected_columns[${table_name}]} -d true -o ${CHECK_COLUMNS_OUTPUT_DIR}/${table_name}.txt"
|
||||
fi
|
||||
|
||||
echo "${table_name}"
|
||||
echo Start: "$(date)"
|
||||
eval "${command}"
|
||||
echo End: "$(date)"
|
||||
echo Total bad rows: $(wc -l ${CHECK_COLUMNS_OUTPUT_DIR}/${table_name}.txt)
|
||||
echo
|
||||
done
|
||||
|
||||
difference=$(($(date +%s)-start_timestamp))
|
||||
echo Time taken: $((difference/86400)):$(date -d@${difference} -u +%H:%M:%S)
|
||||
echo
|
||||
Executable
+122
@@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Usage: compare-versions.sh [-d <output-dir>] <binary-A> <binary-B>
|
||||
#
|
||||
# Compares full statediff output from two versions of the service.
|
||||
# Configure the input data using environment vars.
|
||||
(
|
||||
set -u
|
||||
: $ETHDB_PATH
|
||||
: $ETHDB_ANCIENT
|
||||
: $ETH_GENESIS_BLOCK
|
||||
: $ETH_CHAIN_CONFIG
|
||||
) || exit 1
|
||||
|
||||
# Range of diffs to request
|
||||
range_start=50
|
||||
range_end=100
|
||||
|
||||
# Get the parent directory
|
||||
script_dir=$(readlink -f "$(dirname -- "${BASH_SOURCE[0]}")")
|
||||
|
||||
while getopts d: opt; do
|
||||
case $opt in
|
||||
d) output_dir="$OPTARG"
|
||||
esac
|
||||
done
|
||||
shift $((OPTIND - 1))
|
||||
|
||||
binary_A=$1
|
||||
binary_B=$2
|
||||
shift 2
|
||||
|
||||
if [[ -z $output_dir ]]; then
|
||||
output_dir=$(mktemp -d)
|
||||
fi
|
||||
|
||||
export STATEDIFF_TRIE_WORKERS=32
|
||||
export STATEDIFF_SERVICE_WORKERS=8
|
||||
export STATEDIFF_WORKER_QUEUE_SIZE=1024
|
||||
|
||||
export DATABASE_TYPE=postgres
|
||||
export DATABASE_NAME="cerc_testing"
|
||||
export DATABASE_HOSTNAME="localhost"
|
||||
export DATABASE_PORT=8077
|
||||
export DATABASE_USER="vdbm"
|
||||
export DATABASE_PASSWORD="password"
|
||||
|
||||
export ETH_NODE_ID=test-node
|
||||
export ETH_CLIENT_NAME=test-client
|
||||
export ETH_NETWORK_ID=test-network
|
||||
|
||||
export SERVICE_HTTP_PATH='127.0.0.1:8545'
|
||||
export LOG_LEVEL=debug
|
||||
|
||||
dump_table() {
|
||||
statement="copy (select * from $1) to stdout with csv"
|
||||
docker exec -e PGPASSWORD="$DATABASE_PASSWORD" test-ipld-eth-db-1 \
|
||||
psql -q $DATABASE_NAME -U $DATABASE_USER -c "$statement" | sort -u > "$2/$1.csv"
|
||||
}
|
||||
|
||||
clear_table() {
|
||||
docker exec -e PGPASSWORD="$DATABASE_PASSWORD" test-ipld-eth-db-1 \
|
||||
psql -q $DATABASE_NAME -U $DATABASE_USER -c "truncate $1"
|
||||
}
|
||||
|
||||
tables=(
|
||||
eth.header_cids
|
||||
eth.log_cids
|
||||
eth.receipt_cids
|
||||
eth.state_cids
|
||||
eth.storage_cids
|
||||
eth.transaction_cids
|
||||
eth.uncle_cids
|
||||
ipld.blocks
|
||||
public.nodes
|
||||
)
|
||||
|
||||
for table in "${tables[@]}"; do
|
||||
clear_table $table
|
||||
done
|
||||
|
||||
run_service() {
|
||||
export LOG_FILE=$(mktemp)
|
||||
export LOG_FILE_PATH=$LOG_FILE
|
||||
|
||||
service_binary=$1
|
||||
service_output_dir=$2
|
||||
|
||||
mkdir -p $service_output_dir
|
||||
$service_binary serve &
|
||||
|
||||
until grep "HTTP endpoint opened" $LOG_FILE
|
||||
do sleep 1; done
|
||||
|
||||
$script_dir/request-range.sh $range_start $range_end
|
||||
if E=$?; [[ $E != 0 ]]; then
|
||||
cat $LOG_FILE
|
||||
return $E
|
||||
fi
|
||||
|
||||
echo "Waiting for service to complete requests..."
|
||||
|
||||
until grep \
|
||||
-e "Finished processing block $range_end" \
|
||||
-e "finished processing statediff height $range_end" \
|
||||
$LOG_FILE
|
||||
do sleep 1; done
|
||||
|
||||
kill -INT $!
|
||||
|
||||
mkdir -p $service_output_dir
|
||||
for table in "${tables[@]}"; do
|
||||
dump_table $table $service_output_dir
|
||||
clear_table $table
|
||||
done
|
||||
}
|
||||
|
||||
set -e
|
||||
run_service $binary_A $output_dir/A
|
||||
run_service $binary_B $output_dir/B
|
||||
|
||||
diff -rs $output_dir/A $output_dir/B
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Requires:
|
||||
# COUNT_LINES_LOG
|
||||
# COUNT_LINES_INPUT_DIR
|
||||
# COUNT_LINES_OUTPUT_FILE
|
||||
|
||||
# env file arg
|
||||
ENV=$1
|
||||
echo "Using env file: ${ENV}"
|
||||
|
||||
# read env file
|
||||
export $(grep -v '^#' ${ENV} | xargs)
|
||||
|
||||
# redirect stdout/stderr to a file
|
||||
exec >"${COUNT_LINES_LOG}" 2>&1
|
||||
|
||||
start_timestamp=$(date +%s)
|
||||
|
||||
table_names=(
|
||||
"public.nodes"
|
||||
"public.blocks"
|
||||
"eth.access_list_elements"
|
||||
"eth.log_cids"
|
||||
"eth.state_accounts"
|
||||
"eth.storage_cids"
|
||||
"eth.uncle_cids"
|
||||
"eth.header_cids"
|
||||
"eth.receipt_cids"
|
||||
"eth.state_cids"
|
||||
"eth.transaction_cids"
|
||||
)
|
||||
|
||||
echo "Row counts:" > "${COUNT_LINES_OUTPUT_FILE}"
|
||||
|
||||
for table_name in "${table_names[@]}";
|
||||
do
|
||||
echo "${table_name}";
|
||||
echo Start: "$(date)"
|
||||
wc -l "${COUNT_LINES_INPUT_DIR}"/"${table_name}.csv" >> "${COUNT_LINES_OUTPUT_FILE}"
|
||||
echo End: "$(date)"
|
||||
echo
|
||||
done
|
||||
|
||||
difference=$(($(date +%s)-start_timestamp))
|
||||
echo Time taken: $((difference/86400)):$(date -d@${difference} -u +%H:%M:%S)
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Requires:
|
||||
# DEDUP_LOG
|
||||
# DEDUP_INPUT_DIR
|
||||
# DEDUP_OUTPUT_DIR
|
||||
# DEDUP_SORT_DIR
|
||||
|
||||
# env file arg
|
||||
ENV=$1
|
||||
echo "Using env file: ${ENV}"
|
||||
|
||||
# read env file
|
||||
export $(grep -v '^#' ${ENV} | xargs)
|
||||
|
||||
# redirect stdout/stderr to a file
|
||||
exec >"${DEDUP_LOG}" 2>&1
|
||||
|
||||
# create output dir if not exists
|
||||
mkdir -p "${DEDUP_OUTPUT_DIR}"
|
||||
|
||||
start_timestamp=$(date +%s)
|
||||
|
||||
echo "public.blocks"
|
||||
echo Start: "$(date)"
|
||||
sort -T "${DEDUP_SORT_DIR}" -u "${DEDUP_INPUT_DIR}"/public.blocks.csv -o "${DEDUP_OUTPUT_DIR}"/deduped-public.blocks.csv
|
||||
echo End: "$(date)"
|
||||
echo Total deduped rows: $(wc -l ${DEDUP_OUTPUT_DIR}/deduped-public.blocks.csv)
|
||||
echo
|
||||
|
||||
difference=$(($(date +%s)-start_timestamp))
|
||||
echo Time taken: $((difference/86400)):$(date -d@${difference} -u +%H:%M:%S)
|
||||
|
||||
# NOTE: This script currently only dedups public.blocks output file.
|
||||
# If the output contains blocks that were statediffed more than once, output files for other tables will have to be deduped as well.
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
|
||||
# flags
|
||||
# -i <input-file>: Input data file path
|
||||
# -c <expected-columns>: Expected number of columns in each row of the input file
|
||||
# -o [output-file]: Output destination file path (default: STDOUT)
|
||||
# -d [include-data]: Whether to include the data row in output (true | false) (default: false)
|
||||
|
||||
# eg: ./scripts/find-bad-rows.sh -i eth.state_cids.csv -c 8 -o res.txt -d true
|
||||
# output: 1 9 1500000,xxxxxxxx,0x83952d392f9b0059eea94b10d1a095eefb1943ea91595a16c6698757127d4e1c,,
|
||||
# baglacgzasvqcntdahkxhufdnkm7a22s2eetj6mx6nzkarwxtkvy4x3bubdgq,\x0f,0,f,/blocks/,
|
||||
# DMQJKYBGZRQDVLT2CRWVGPQNNJNCCJU7GL7G4VAI3LZVK4OL5Q2ARTI
|
||||
|
||||
while getopts i:c:o:d: OPTION
|
||||
do
|
||||
case "${OPTION}" in
|
||||
i) inputFile=${OPTARG};;
|
||||
c) expectedColumns=${OPTARG};;
|
||||
o) outputFile=${OPTARG};;
|
||||
d) data=${OPTARG};;
|
||||
esac
|
||||
done
|
||||
|
||||
timestamp=$(date +%s)
|
||||
|
||||
# if data requested, dump row number, number of columns and the row
|
||||
if [ "${data}" = true ] ; then
|
||||
if [ -z "${outputFile}" ]; then
|
||||
awk -F"," "NF!=${expectedColumns} {print NR, NF, \$0}" < ${inputFile}
|
||||
else
|
||||
awk -F"," "NF!=${expectedColumns} {print NR, NF, \$0}" < ${inputFile} > ${outputFile}
|
||||
fi
|
||||
# else, dump only row number, number of columns
|
||||
else
|
||||
if [ -z "${outputFile}" ]; then
|
||||
awk -F"," "NF!=${expectedColumns} {print NR, NF}" < ${inputFile}
|
||||
else
|
||||
awk -F"," "NF!=${expectedColumns} {print NR, NF}" < ${inputFile} > ${outputFile}
|
||||
fi
|
||||
fi
|
||||
|
||||
difference=$(($(date +%s)-timestamp))
|
||||
echo Time taken: $(date -d@${difference} -u +%H:%M:%S)
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -eu
|
||||
|
||||
FROM=$1
|
||||
TO=$2
|
||||
URL='127.0.0.1:8545'
|
||||
|
||||
DATA='{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "statediff_writeStateDiffsInRange",
|
||||
"params": ['"$FROM"', '"$TO"', {
|
||||
"includeBlock": true,
|
||||
"includeReceipts": true,
|
||||
"includeTD": true,
|
||||
"includeCode": true
|
||||
}
|
||||
],
|
||||
"id": 1
|
||||
}'
|
||||
|
||||
exec curl -s $URL -X POST -H 'Content-Type: application/json' --data "$DATA"
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Requires:
|
||||
# IMPORT_LOG
|
||||
# IMPORT_INPUT_DIR
|
||||
# IMPORT_INPUT_DEDUP_DIR
|
||||
# TIMESCALEDB_WORKERS
|
||||
# DATABASE_USER
|
||||
# DATABASE_HOSTNAME
|
||||
# DATABASE_PORT
|
||||
# DATABASE_NAME
|
||||
# DATABASE_PASSWORD
|
||||
|
||||
DEFAULT_TIMESCALEDB_WORKERS=8
|
||||
|
||||
# env file arg
|
||||
ENV=$1
|
||||
echo "Using env file: ${ENV}"
|
||||
|
||||
# read env file
|
||||
export $(grep -v '^#' ${ENV} | xargs)
|
||||
|
||||
if [ "$TIMESCALEDB_WORKERS" = "" ]; then
|
||||
TIMESCALEDB_WORKERS=$DEFAULT_TIMESCALEDB_WORKERS
|
||||
fi
|
||||
|
||||
# redirect stdout/stderr to a file
|
||||
exec >"${IMPORT_LOG}" 2>&1
|
||||
|
||||
start_timestamp=$(date +%s)
|
||||
|
||||
declare -a tables
|
||||
# schema-table-copyOptions
|
||||
tables=(
|
||||
"public-nodes"
|
||||
"public-blocks"
|
||||
"eth-access_list_elements"
|
||||
"eth-log_cids-FORCE NOT NULL topic0, topic1, topic2, topic3 CSV"
|
||||
"eth-state_accounts"
|
||||
"eth-storage_cids-FORCE NOT NULL storage_leaf_key CSV"
|
||||
"eth-uncle_cids"
|
||||
"eth-header_cids"
|
||||
"eth-receipt_cids-FORCE NOT NULL post_state, contract, contract_hash CSV"
|
||||
"eth-state_cids-FORCE NOT NULL state_leaf_key CSV"
|
||||
"eth-transaction_cids-FORCE NOT NULL dst CSV"
|
||||
)
|
||||
|
||||
for elem in "${tables[@]}";
|
||||
do
|
||||
IFS='-' read -a arr <<< "${elem}"
|
||||
|
||||
if [ "${arr[0]}.${arr[1]}" = "public.blocks" ];
|
||||
then
|
||||
copy_command="timescaledb-parallel-copy --connection \"host=${DATABASE_HOSTNAME} port=${DATABASE_PORT} user=${DATABASE_USER} password=${DATABASE_PASSWORD} sslmode=disable\" --db-name ${DATABASE_NAME} --schema ${arr[0]} --table ${arr[1]} --file ${IMPORT_INPUT_DEDUP_DIR}/deduped-${arr[0]}.${arr[1]}.csv --workers ${TIMESCALEDB_WORKERS} --reporting-period 300s"
|
||||
else
|
||||
copy_command="timescaledb-parallel-copy --connection \"host=${DATABASE_HOSTNAME} port=${DATABASE_PORT} user=${DATABASE_USER} password=${DATABASE_PASSWORD} sslmode=disable\" --db-name ${DATABASE_NAME} --schema ${arr[0]} --table ${arr[1]} --file ${IMPORT_INPUT_DIR}/${arr[0]}.${arr[1]}.csv --workers ${TIMESCALEDB_WORKERS} --reporting-period 300s"
|
||||
fi
|
||||
|
||||
if [ "${arr[2]}" != "" ];
|
||||
then
|
||||
copy_with_options="${copy_command} --copy-options \"${arr[2]}\""
|
||||
else
|
||||
copy_with_options=${copy_command}
|
||||
fi
|
||||
|
||||
echo "${arr[0]}.${arr[1]}"
|
||||
echo Start: "$(date)"
|
||||
eval "${copy_with_options}"
|
||||
echo End: "$(date)"
|
||||
echo
|
||||
done
|
||||
|
||||
difference=$(($(date +%s)-start_timestamp))
|
||||
echo Time taken: $((difference/86400)):$(date -d@${difference} -u +%H:%M:%S)
|
||||
echo
|
||||
Regular → Executable
+57
-6
@@ -1,11 +1,62 @@
|
||||
#!/bin/sh
|
||||
#!/bin/bash
|
||||
# Exit if the variable tests fail
|
||||
set -e
|
||||
set +x
|
||||
set -o pipefail
|
||||
|
||||
if [[ -n "$CERC_SCRIPT_DEBUG" ]]; then
|
||||
set -x
|
||||
fi
|
||||
|
||||
# Check the database variables are set
|
||||
test $VDB_COMMAND
|
||||
set +e
|
||||
test "$VDB_COMMAND"
|
||||
|
||||
echo "Running the statediff service"
|
||||
./eth-statediff-service ${VDB_COMMAND} --config=config.toml
|
||||
# docker must be run in privileged mode for mounts to work
|
||||
echo "Setting up /app/geth-rw overlayed onto /app/geth-ro"
|
||||
mkdir -p /tmp/overlay
|
||||
mount -t tmpfs tmpfs /tmp/overlay
|
||||
mkdir -p /tmp/overlay/upper
|
||||
mkdir -p /tmp/overlay/work
|
||||
mkdir -p /app/geth-rw
|
||||
|
||||
mount -t overlay overlay -o lowerdir=/app/geth-ro,upperdir=/tmp/overlay/upper,workdir=/tmp/overlay/work /app/geth-rw
|
||||
|
||||
mkdir /var/run/statediff
|
||||
cd /var/run/statediff
|
||||
|
||||
SETUID=""
|
||||
if [[ -n "$TARGET_UID" ]] && [[ -n "$TARGET_GID" ]]; then
|
||||
SETUID="su-exec $TARGET_UID:$TARGET_GID"
|
||||
chown -R $TARGET_UID:$TARGET_GID /var/run/statediff
|
||||
fi
|
||||
|
||||
START_TIME=`date -u +"%Y-%m-%dT%H:%M:%SZ"`
|
||||
echo "Running the statediff service" && \
|
||||
if [[ ! -z "$LOG_FILE" ]]; then
|
||||
$SETUID /app/eth-statediff-service "$VDB_COMMAND" --config=/app/config.toml $* |& $SETUID tee ${LOG_FILE}.console
|
||||
rc=$?
|
||||
else
|
||||
$SETUID /app/eth-statediff-service "$VDB_COMMAND" --config=/app/config.toml $*
|
||||
rc=$?
|
||||
fi
|
||||
STOP_TIME=`date -u +"%Y-%m-%dT%H:%M:%SZ"`
|
||||
|
||||
if [ $rc -eq 0 ] && [ "$VDB_COMMAND" == "serve" ] && [ "$PRERUN_ONLY" == "true" ] && [ ! -z "$PRERUN_RANGE_START" ] && [ ! -z "$PRERUN_RANGE_STOP" ] && [ ! -z "$DATABASE_FILE_CSV_DIR" ] && [ "$DATABASE_FILE_MODE" == "csv" ]; then
|
||||
cat >metadata.json <<EOF
|
||||
{
|
||||
"type": "statediff",
|
||||
"range": { "start": $PRERUN_RANGE_START, "stop": $PRERUN_RANGE_STOP },
|
||||
"nodeId": "$ETH_NODE_ID",
|
||||
"genesisBlock": "$ETH_GENESIS_BLOCK",
|
||||
"networkId": "$ETH_NETWORK_ID",
|
||||
"chainId": "$ETH_CHAIN_ID",
|
||||
"time": { "start": "$START_TIME", "stop": "$STOP_TIME" }
|
||||
}
|
||||
EOF
|
||||
if [[ -n "$TARGET_UID" ]] && [[ -n "$TARGET_GID" ]]; then
|
||||
echo 'metadata.json' | cpio -p --owner $TARGET_UID:$TARGET_GID $DATABASE_FILE_CSV_DIR
|
||||
else
|
||||
cp metadata.json $DATABASE_FILE_CSV_DIR
|
||||
fi
|
||||
fi
|
||||
|
||||
exit $rc
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Config file for github workflow
|
||||
|
||||
[server]
|
||||
ipcPath = ".ipc"
|
||||
httpPath = "0.0.0.0:8545"
|
||||
|
||||
[statediff]
|
||||
serviceWorkers = 1
|
||||
workerQueueSize = 1024
|
||||
trieWorkers = 4
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[database]
|
||||
name = "cerc_testing"
|
||||
hostname = "localhost"
|
||||
port = 8077
|
||||
user = "vdbm"
|
||||
password = "password"
|
||||
type = "postgres"
|
||||
driver = "sqlx"
|
||||
|
||||
[cache]
|
||||
database = 1024
|
||||
trie = 1024
|
||||
|
||||
[ethereum]
|
||||
nodeID = "test-node"
|
||||
clientName = "test-eth-statediff-service"
|
||||
networkID = "test-network"
|
||||
chainID = 41337
|
||||
@@ -0,0 +1,23 @@
|
||||
services:
|
||||
migrations:
|
||||
restart: on-failure
|
||||
depends_on:
|
||||
- ipld-eth-db
|
||||
image: git.vdb.to/cerc-io/ipld-eth-db/ipld-eth-db:v5.3.0-alpha
|
||||
environment:
|
||||
DATABASE_USER: "vdbm"
|
||||
DATABASE_NAME: "cerc_testing"
|
||||
DATABASE_PASSWORD: "password"
|
||||
DATABASE_HOSTNAME: "ipld-eth-db"
|
||||
DATABASE_PORT: 5432
|
||||
|
||||
ipld-eth-db:
|
||||
image: timescale/timescaledb:latest-pg14
|
||||
restart: always
|
||||
command: ["postgres", "-c", "log_statement=all"]
|
||||
environment:
|
||||
POSTGRES_USER: "vdbm"
|
||||
POSTGRES_DB: "cerc_testing"
|
||||
POSTGRES_PASSWORD: "password"
|
||||
ports:
|
||||
- 127.0.0.1:8077:5432
|
||||
@@ -0,0 +1,30 @@
|
||||
// VulcanizeDB
|
||||
// Copyright © 2021 Vulcanize
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package version
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
major = 3 // major version component of the current release
|
||||
minor = 0 // minor version component of the current release
|
||||
patch = 0 // patch version component of the current release
|
||||
)
|
||||
|
||||
// Version holds the textual version string.
|
||||
var Version = func() string {
|
||||
return fmt.Sprintf("%d.%d.%d", major, minor, patch)
|
||||
}()
|
||||
Reference in New Issue
Block a user