good morning!!!!

Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • github/maticnetwork/bor
  • open/bor
2 results
Show changes
Commits on Source (141)
Showing
with 609 additions and 139 deletions
...@@ -6,10 +6,15 @@ jobs: ...@@ -6,10 +6,15 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Install Go - name: Install Go
uses: actions/setup-go@v2.1.3 uses: actions/setup-go@v2
with: with:
go-version: 1.16.7 go-version: 1.17
- name: "Build binaries" - name: "Build binaries"
run: make all run: make all
- name: "Run tests" - name: "Run tests"
run: make test run: make test
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
with:
file: ./cover.out
name: Docker Images For Latest Branches
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build docker image
env:
DOCKERHUB: ${{ secrets.DOCKERHUB }}
DOCKERHUB_KEY: ${{ secrets.DOCKERHUB_KEY }}
run: |
set -x
ls -l
echo "Docker login"
docker login -u $DOCKERHUB -p $DOCKERHUB_KEY
echo "Running build"
docker build -t maticnetwork/bor:${GITHUB_REF/refs\/heads\//} .
echo "Pushing image"
docker push maticnetwork/bor:${GITHUB_REF/refs\/heads\//}
echo "Done"
...@@ -2,8 +2,12 @@ name: Bor Docker Image CI ...@@ -2,8 +2,12 @@ name: Bor Docker Image CI
on: on:
push: push:
branches-ignore:
- '**'
tags: tags:
- 'v*.*.*' - 'v*.*.*'
# to be used by fork patch-releases ^^
- 'v*.*.*-*'
jobs: jobs:
build: build:
...@@ -19,7 +23,7 @@ jobs: ...@@ -19,7 +23,7 @@ jobs:
echo "Docker login" echo "Docker login"
docker login -u $DOCKERHUB -p $DOCKERHUB_KEY docker login -u $DOCKERHUB -p $DOCKERHUB_KEY
echo "running build" echo "running build"
docker build -t maticnetwork/bor:${GITHUB_REF/refs\/tags\//} . docker build -f Dockerfile.classic -t maticnetwork/bor:${GITHUB_REF/refs\/tags\//} .
echo "pushing image" echo "pushing image"
docker push maticnetwork/bor:${GITHUB_REF/refs\/tags\//} docker push maticnetwork/bor:${GITHUB_REF/refs\/tags\//}
echo "DONE!" echo "DONE!"
name: Linux package
on:
push:
tags:
- "v*.*.*"
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: 1.17
- name: Set up Ruby 2.6
uses: actions/setup-ruby@v1
with:
ruby-version: 2.6
- name: Retrieve release version
run: |
echo "RELEASE_VERSION=${GITHUB_REF/refs\/tags\/v/}" >> $GITHUB_ENV
- name: Build package
run: |
set -x
echo "Release version: ${{ env.RELEASE_VERSION }}"
sudo apt-get -yqq install libpq-dev build-essential
gem install --no-document fpm
fpm --version
make bor-all
fpm -s dir -t deb --deb-user root --deb-group root -n matic-bor -v ${{ env.RELEASE_VERSION }} \
build/bin/bor=/usr/bin/ \
build/bin/bootnode=/usr/bin/
mkdir packages-v${{ env.RELEASE_VERSION }}
mv matic-bor_${{ env.RELEASE_VERSION }}_amd64.deb packages-v${{ env.RELEASE_VERSION }}/
ls packages-v${{ env.RELEASE_VERSION }}/
- name: S3 upload
uses: jakejarvis/s3-sync-action@master
with:
args: --acl public-read
env:
AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: "us-east-1" # optional: defaults to us-east-1
SOURCE_DIR: "packages-v${{ env.RELEASE_VERSION }}"
DEST_DIR: "v${{ env.RELEASE_VERSION }}"
- name: Slack Notification
uses: rtCamp/action-slack-notify@v2.0.0
env:
SLACK_CHANNEL: code-releases
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
SLACK_TITLE: "New linux package for Bor v${{ env.RELEASE_VERSION }} just got released"
SLACK_MESSAGE: "Package has been uploaded to S3 bucket for public use and available at https://matic-public.s3.amazonaws.com/v${{ env.RELEASE_VERSION }}/matic-bor_${{ env.RELEASE_VERSION }}_amd64.deb"
name: Release
on:
push:
branches-ignore:
- '**'
tags:
- 'v*.*.*'
# to be used by fork patch-releases ^^
- 'v*.*.*-*'
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@master
with:
go-version: 1.17.x
- name: Prepare
id: prepare
run: |
TAG=${GITHUB_REF#refs/tags/}
echo ::set-output name=tag_name::${TAG}
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Run GoReleaser
run: |
make release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ steps.prepare.outputs.tag_name }}
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
DOCKER_USERNAME: ${{ secrets.DOCKERHUB }}
DOCKER_PASSWORD: ${{ secrets.DOCKERHUB_KEY }}
...@@ -47,3 +47,7 @@ profile.cov ...@@ -47,3 +47,7 @@ profile.cov
/dashboard/assets/package-lock.json /dashboard/assets/package-lock.json
**/yarn-error.log **/yarn-error.log
./test
./bor-debug-*
dist
project_name: bor
release:
disable: false
draft: true
prerelease: auto
builds:
- id: darwin-amd64
main: ./cmd/geth
binary: bor
goos:
- darwin
goarch:
- amd64
env:
- CC=o64-clang
- CXX=o64-clang++
tags:
- netgo
ldflags:
-s -w
- id: darwin-arm64
main: ./cmd/geth
binary: bor
goos:
- darwin
goarch:
- arm64
env:
- CC=oa64-clang
- CXX=oa64-clang++
tags:
- netgo
ldflags:
-s -w
- id: linux-amd64
main: ./cmd/geth
binary: bor
goos:
- linux
goarch:
- amd64
env:
- CC=gcc
- CXX=g++
tags:
- netgo
ldflags:
# We need to build a static binary because we are building in a glibc based system and running in a musl container
-s -w -extldflags "-static"
- id: linux-arm64
main: ./cmd/geth
binary: bor
goos:
- linux
goarch:
- arm64
env:
- CC=aarch64-linux-gnu-gcc
- CXX=aarch64-linux-gnu-g++
tags:
- netgo
ldflags:
# We need to build a static binary because we are building in a glibc based system and running in a musl container
-s -w -extldflags "-static"
nfpms:
- vendor: 0xPolygon
homepage: https://polygon.technology
maintainer: Polygon Team <team@polygon.technology>
description: Polygon Blockchain
license: GPLv3 LGPLv3
formats:
- apk
- deb
- rpm
contents:
- src: builder/files/bor.service
dst: /lib/systemd/system/bor.service
type: config
- src: builder/files/genesis-mainnet-v1.json
dst: /etc/bor/genesis-mainnet-v1.json
type: config
- src: builder/files/genesis-testnet-v4.json
dst: /etc/bor/genesis-testnet-v4.json
type: config
overrides:
rpm:
replacements:
amd64: x86_64
snapshot:
name_template: "{{ .Tag }}.next"
dockers:
- image_templates:
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-amd64
dockerfile: Dockerfile.release
use: buildx
goarch: amd64
ids:
- linux-amd64
build_flag_templates:
- --platform=linux/amd64
extra_files:
- builder/files/genesis-mainnet-v1.json
- builder/files/genesis-testnet-v4.json
- image_templates:
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-arm64
dockerfile: Dockerfile.release
use: buildx
goarch: arm64
ids:
- linux-arm64
build_flag_templates:
- --platform=linux/arm64/v8
extra_files:
- builder/files/genesis-mainnet-v1.json
- builder/files/genesis-testnet-v4.json
docker_manifests:
- name_template: 0xpolygon/{{ .ProjectName }}:{{ .Version }}
image_templates:
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-amd64
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-arm64
- name_template: 0xpolygon/{{ .ProjectName }}:latest
image_templates:
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-amd64
- 0xpolygon/{{ .ProjectName }}:{{ .Version }}-arm64
announce:
slack:
enabled: true
# The name of the channel that the user selected as a destination for webhook messages.
channel: '#code-releases'
# Build Geth in a stock Go builder container FROM golang:latest
FROM golang:1.17-alpine as builder
RUN apk add --no-cache make gcc musl-dev linux-headers git bash ARG BOR_DIR=/bor
ENV BOR_DIR=$BOR_DIR
ADD . /bor RUN apt-get update -y && apt-get upgrade -y \
RUN cd /bor && make bor-all && apt install build-essential git -y \
&& mkdir -p /bor
CMD ["/bin/bash"] WORKDIR ${BOR_DIR}
COPY . .
RUN make bor-all
# Pull Bor into a second stage deploy alpine container ENV SHELL /bin/bash
FROM alpine:latest EXPOSE 8545 8546 8547 30303 30303/udp
RUN apk add --no-cache ca-certificates ENTRYPOINT ["bor"]
COPY --from=builder /bor/build/bin/bor /usr/local/bin/
COPY --from=builder /bor/build/bin/bootnode /usr/local/bin/
EXPOSE 8545 8546 8547 30303 30303/udp
\ No newline at end of file
...@@ -9,7 +9,10 @@ RUN cd /bor && make bor-all ...@@ -9,7 +9,10 @@ RUN cd /bor && make bor-all
# Pull all binaries into a second stage deploy alpine container # Pull all binaries into a second stage deploy alpine container
FROM alpine:latest FROM alpine:latest
RUN apk add --no-cache ca-certificates RUN set -x \
&& apk add --update --no-cache \
ca-certificates \
&& rm -rf /var/cache/apk/*
COPY --from=builder /bor/build/bin/* /usr/local/bin/ COPY --from=builder /bor/build/bin/* /usr/local/bin/
EXPOSE 8545 8546 30303 30303/udp EXPOSE 8545 8546 30303 30303/udp
\ No newline at end of file
# Build Geth in a stock Go builder container
FROM golang:1.17-alpine as builder
RUN apk add --no-cache make gcc musl-dev linux-headers git bash
ADD . /bor
RUN cd /bor && make bor-all
CMD ["/bin/bash"]
# Pull Bor into a second stage deploy alpine container
FROM alpine:latest
RUN apk add --no-cache ca-certificates
COPY --from=builder /bor/build/bin/bor /usr/local/bin/
COPY --from=builder /bor/build/bin/bootnode /usr/local/bin/
EXPOSE 8545 8546 8547 30303 30303/udp
FROM alpine:3.14
RUN apk add --no-cache ca-certificates && \
mkdir -p /etc/bor
COPY bor /usr/local/bin/
COPY builder/files/genesis-mainnet-v1.json /etc/bor/
COPY builder/files/genesis-testnet-v4.json /etc/bor/
EXPOSE 8545 8546 8547 30303 30303/udp
ENTRYPOINT ["bor"]
...@@ -25,6 +25,9 @@ bor-all: ...@@ -25,6 +25,9 @@ bor-all:
cp $(GOBIN)/geth $(GOBIN)/bor cp $(GOBIN)/geth $(GOBIN)/bor
cp $(GOBIN)/* $(GOPATH)/bin/ cp $(GOBIN)/* $(GOPATH)/bin/
protoc:
protoc --go_out=. --go-grpc_out=. ./command/server/proto/*.proto
geth: geth:
$(GORUN) build/ci.go install ./cmd/geth $(GORUN) build/ci.go install ./cmd/geth
@echo "Done building." @echo "Done building."
...@@ -45,10 +48,9 @@ ios: ...@@ -45,10 +48,9 @@ ios:
@echo "Done building." @echo "Done building."
@echo "Import \"$(GOBIN)/Geth.framework\" to use the library." @echo "Import \"$(GOBIN)/Geth.framework\" to use the library."
test: all test:
# $(GORUN) build/ci.go test # Skip mobile and cmd tests since they are being deprecated
go test github.com/ethereum/go-ethereum/consensus/bor go test -v $$(go list ./... | grep -v go-ethereum/cmd/) -cover -coverprofile=cover.out
go test github.com/ethereum/go-ethereum/tests/bor
lint: ## Run linters. lint: ## Run linters.
$(GORUN) build/ci.go lint $(GORUN) build/ci.go lint
...@@ -160,3 +162,37 @@ geth-windows-amd64: ...@@ -160,3 +162,37 @@ geth-windows-amd64:
$(GORUN) build/ci.go xgo -- --go=$(GO) --targets=windows/amd64 -v ./cmd/geth $(GORUN) build/ci.go xgo -- --go=$(GO) --targets=windows/amd64 -v ./cmd/geth
@echo "Windows amd64 cross compilation done:" @echo "Windows amd64 cross compilation done:"
@ls -ld $(GOBIN)/geth-windows-* | grep amd64 @ls -ld $(GOBIN)/geth-windows-* | grep amd64
PACKAGE_NAME := github.com/maticnetwork/bor
GOLANG_CROSS_VERSION ?= v1.17.2
.PHONY: release-dry-run
release-dry-run:
@docker run \
--rm \
--privileged \
-e CGO_ENABLED=1 \
-e GITHUB_TOKEN \
-e DOCKER_USERNAME \
-e DOCKER_PASSWORD \
-v /var/run/docker.sock:/var/run/docker.sock \
-v `pwd`:/go/src/$(PACKAGE_NAME) \
-w /go/src/$(PACKAGE_NAME) \
ghcr.io/troian/golang-cross:${GOLANG_CROSS_VERSION} \
--rm-dist --skip-validate --skip-publish
.PHONY: release
release:
@docker run \
--rm \
--privileged \
-e CGO_ENABLED=1 \
-e GITHUB_TOKEN \
-e DOCKER_USERNAME \
-e DOCKER_PASSWORD \
-e SLACK_WEBHOOK \
-v /var/run/docker.sock:/var/run/docker.sock \
-v `pwd`:/go/src/$(PACKAGE_NAME) \
-w /go/src/$(PACKAGE_NAME) \
ghcr.io/troian/golang-cross:${GOLANG_CROSS_VERSION} \
--rm-dist --skip-validate
...@@ -113,6 +113,12 @@ them using your favourite package manager. Once the dependencies are installed, ...@@ -113,6 +113,12 @@ them using your favourite package manager. Once the dependencies are installed,
<hr style="margin-top: 3em; margin-bottom: 3em;"> <hr style="margin-top: 3em; margin-bottom: 3em;">
Build the beta client:
```shell
go build -o bor-beta command/*.go
```
## License ## License
The go-ethereum library (i.e. all code outside of the `cmd` directory) is licensed under the The go-ethereum library (i.e. all code outside of the `cmd` directory) is licensed under the
......
[Unit]
Description=bor
StartLimitIntervalSec=500
StartLimitBurst=5
[Service]
Restart=on-failure
RestartSec=5s
ExecStart=/usr/local/bin/bor \
--bor-mumbai \
# --bor-mainnet \
--datadir /var/lib/bor/data \
--bootnodes "enode://0cb82b395094ee4a2915e9714894627de9ed8498fb881cec6db7c65e8b9a5bd7f2f25cc84e71e89d0947e51c76e85d0847de848c7782b13c0255247a6758178c@44.232.55.71:30303,enode://88116f4295f5a31538ae409e4d44ad40d22e44ee9342869e7d68bdec55b0f83c1530355ce8b41fbec0928a7d75a5745d528450d30aec92066ab6ba1ee351d710@159.203.9.164:30303"
# Validator params
# Uncomment and configure the following lines in case you run a validator
# --keystore /var/lib/bor/keystore \
# --unlock [VALIDATOR ADDRESS] \
# --password /var/lib/bor/password.txt \
# --allow-insecure-unlock \
# --nodiscover --maxpeers 1 \
# --mine
Type=simple
User=root
KillSignal=SIGINT
TimeoutStopSec=120
[Install]
WantedBy=multi-user.target
This diff is collapsed.
This diff is collapsed.
package main
import (
"os"
"github.com/ethereum/go-ethereum/internal/cli"
)
func main() {
os.Exit(cli.Run(os.Args[1:]))
}
...@@ -347,7 +347,7 @@ func setDefaultMumbaiGethConfig(ctx *cli.Context, config *gethConfig) { ...@@ -347,7 +347,7 @@ func setDefaultMumbaiGethConfig(ctx *cli.Context, config *gethConfig) {
config.Node.HTTPPort = 8545 config.Node.HTTPPort = 8545
config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc" config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"} config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
config.Eth.SyncMode = downloader.SnapSync config.Eth.SyncMode = downloader.FullSync
config.Eth.NetworkId = 80001 config.Eth.NetworkId = 80001
config.Eth.Miner.GasCeil = 20000000 config.Eth.Miner.GasCeil = 20000000
//--miner.gastarget is depreceated, No longed used //--miner.gastarget is depreceated, No longed used
...@@ -370,7 +370,7 @@ func setDefaultBorMainnetGethConfig(ctx *cli.Context, config *gethConfig) { ...@@ -370,7 +370,7 @@ func setDefaultBorMainnetGethConfig(ctx *cli.Context, config *gethConfig) {
config.Node.HTTPPort = 8545 config.Node.HTTPPort = 8545
config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc" config.Node.IPCPath = utils.MakeDataDir(ctx) + "/bor.ipc"
config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"} config.Node.HTTPModules = []string{"eth", "net", "web3", "txpool", "bor"}
config.Eth.SyncMode = downloader.SnapSync config.Eth.SyncMode = downloader.FullSync
config.Eth.NetworkId = 137 config.Eth.NetworkId = 137
config.Eth.Miner.GasCeil = 20000000 config.Eth.Miner.GasCeil = 20000000
//--miner.gastarget is depreceated, No longed used //--miner.gastarget is depreceated, No longed used
......
...@@ -1645,13 +1645,11 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { ...@@ -1645,13 +1645,11 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
cfg.NetworkId = 80001 cfg.NetworkId = 80001
} }
cfg.Genesis = core.DefaultMumbaiGenesisBlock() cfg.Genesis = core.DefaultMumbaiGenesisBlock()
SetDNSDiscoveryDefaults(cfg, params.MumbaiGenesisHash)
case ctx.GlobalBool(BorMainnetFlag.Name): case ctx.GlobalBool(BorMainnetFlag.Name):
if !ctx.GlobalIsSet(BorMainnetFlag.Name) { if !ctx.GlobalIsSet(BorMainnetFlag.Name) {
cfg.NetworkId = 137 cfg.NetworkId = 137
} }
cfg.Genesis = core.DefaultBorMainnetGenesisBlock() cfg.Genesis = core.DefaultBorMainnetGenesisBlock()
SetDNSDiscoveryDefaults(cfg, params.BorMainnetGenesisHash)
case ctx.GlobalBool(DeveloperFlag.Name): case ctx.GlobalBool(DeveloperFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) { if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
cfg.NetworkId = 1337 cfg.NetworkId = 1337
......
...@@ -116,6 +116,9 @@ var ( ...@@ -116,6 +116,9 @@ var (
// errOutOfRangeChain is returned if an authorization list is attempted to // errOutOfRangeChain is returned if an authorization list is attempted to
// be modified via out-of-range or non-contiguous headers. // be modified via out-of-range or non-contiguous headers.
errOutOfRangeChain = errors.New("out of range or non-contiguous chain") errOutOfRangeChain = errors.New("out of range or non-contiguous chain")
// errShutdownDetected is returned if a shutdown was detected
errShutdownDetected = errors.New("shutdown detected")
) )
// SignerFn is a signer callback function to request a header to be signed by a // SignerFn is a signer callback function to request a header to be signed by a
...@@ -123,7 +126,7 @@ var ( ...@@ -123,7 +126,7 @@ var (
type SignerFn func(accounts.Account, string, []byte) ([]byte, error) type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
// ecrecover extracts the Ethereum account address from a signed header. // ecrecover extracts the Ethereum account address from a signed header.
func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) { func ecrecover(header *types.Header, sigcache *lru.ARCCache, c *params.BorConfig) (common.Address, error) {
// If the signature's already cached, return that // If the signature's already cached, return that
hash := header.Hash() hash := header.Hash()
if address, known := sigcache.Get(hash); known { if address, known := sigcache.Get(hash); known {
...@@ -136,7 +139,7 @@ func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, er ...@@ -136,7 +139,7 @@ func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, er
signature := header.Extra[len(header.Extra)-extraSeal:] signature := header.Extra[len(header.Extra)-extraSeal:]
// Recover the public key and the Ethereum address // Recover the public key and the Ethereum address
pubkey, err := crypto.Ecrecover(SealHash(header).Bytes(), signature) pubkey, err := crypto.Ecrecover(SealHash(header, c).Bytes(), signature)
if err != nil { if err != nil {
return common.Address{}, err return common.Address{}, err
} }
...@@ -148,15 +151,15 @@ func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, er ...@@ -148,15 +151,15 @@ func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, er
} }
// SealHash returns the hash of a block prior to it being sealed. // SealHash returns the hash of a block prior to it being sealed.
func SealHash(header *types.Header) (hash common.Hash) { func SealHash(header *types.Header, c *params.BorConfig) (hash common.Hash) {
hasher := sha3.NewLegacyKeccak256() hasher := sha3.NewLegacyKeccak256()
encodeSigHeader(hasher, header) encodeSigHeader(hasher, header, c)
hasher.Sum(hash[:0]) hasher.Sum(hash[:0])
return hash return hash
} }
func encodeSigHeader(w io.Writer, header *types.Header) { func encodeSigHeader(w io.Writer, header *types.Header, c *params.BorConfig) {
err := rlp.Encode(w, []interface{}{ enc := []interface{}{
header.ParentHash, header.ParentHash,
header.UncleHash, header.UncleHash,
header.Coinbase, header.Coinbase,
...@@ -172,8 +175,13 @@ func encodeSigHeader(w io.Writer, header *types.Header) { ...@@ -172,8 +175,13 @@ func encodeSigHeader(w io.Writer, header *types.Header) {
header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short header.Extra[:len(header.Extra)-65], // Yes, this will panic if extra is too short
header.MixDigest, header.MixDigest,
header.Nonce, header.Nonce,
}) }
if err != nil { if c.IsJaipur(header.Number.Uint64()) {
if header.BaseFee != nil {
enc = append(enc, header.BaseFee)
}
}
if err := rlp.Encode(w, enc); err != nil {
panic("can't encode: " + err.Error()) panic("can't encode: " + err.Error())
} }
} }
...@@ -182,12 +190,12 @@ func encodeSigHeader(w io.Writer, header *types.Header) { ...@@ -182,12 +190,12 @@ func encodeSigHeader(w io.Writer, header *types.Header) {
func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64 { func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64 {
// When the block is the first block of the sprint, it is expected to be delayed by `producerDelay`. // When the block is the first block of the sprint, it is expected to be delayed by `producerDelay`.
// That is to allow time for block propagation in the last sprint // That is to allow time for block propagation in the last sprint
delay := c.Period delay := c.CalculatePeriod(number)
if number%c.Sprint == 0 { if number%c.Sprint == 0 {
delay = c.ProducerDelay delay = c.ProducerDelay
} }
if succession > 0 { if succession > 0 {
delay += uint64(succession) * c.BackupMultiplier delay += uint64(succession) * c.CalculateBackupMultiplier(number)
} }
return delay return delay
} }
...@@ -199,9 +207,9 @@ func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint6 ...@@ -199,9 +207,9 @@ func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint6
// Note, the method requires the extra data to be at least 65 bytes, otherwise it // Note, the method requires the extra data to be at least 65 bytes, otherwise it
// panics. This is done to avoid accidentally using both forms (signature present // panics. This is done to avoid accidentally using both forms (signature present
// or not), which could be abused to produce different hashes for the same header. // or not), which could be abused to produce different hashes for the same header.
func BorRLP(header *types.Header) []byte { func BorRLP(header *types.Header, c *params.BorConfig) []byte {
b := new(bytes.Buffer) b := new(bytes.Buffer)
encodeSigHeader(b, header) encodeSigHeader(b, header, c)
return b.Bytes() return b.Bytes()
} }
...@@ -267,13 +275,20 @@ func New( ...@@ -267,13 +275,20 @@ func New(
WithoutHeimdall: withoutHeimdall, WithoutHeimdall: withoutHeimdall,
} }
// make sure we can decode all the GenesisAlloc in the BorConfig.
for key, genesisAlloc := range c.config.BlockAlloc {
if _, err := decodeGenesisAlloc(genesisAlloc); err != nil {
panic(fmt.Sprintf("BUG: Block alloc '%s' in genesis is not correct: %v", key, err))
}
}
return c return c
} }
// Author implements consensus.Engine, returning the Ethereum address recovered // Author implements consensus.Engine, returning the Ethereum address recovered
// from the signature in the header's extra-data section. // from the signature in the header's extra-data section.
func (c *Bor) Author(header *types.Header) (common.Address, error) { func (c *Bor) Author(header *types.Header) (common.Address, error) {
return ecrecover(header, c.signatures) return ecrecover(header, c.signatures, c.config)
} }
// VerifyHeader checks whether a header conforms to the consensus rules. // VerifyHeader checks whether a header conforms to the consensus rules.
...@@ -346,6 +361,11 @@ func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Head ...@@ -346,6 +361,11 @@ func (c *Bor) verifyHeader(chain consensus.ChainHeaderReader, header *types.Head
return errInvalidDifficulty return errInvalidDifficulty
} }
} }
// Verify that the gas limit is <= 2^63-1
cap := uint64(0x7fffffffffffffff)
if header.GasLimit > cap {
return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, cap)
}
// If all checks passed, validate any special fields for hard forks // If all checks passed, validate any special fields for hard forks
if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil { if err := misc.VerifyForkHashes(chain.Config(), header, false); err != nil {
return err return err
...@@ -389,7 +409,24 @@ func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *t ...@@ -389,7 +409,24 @@ func (c *Bor) verifyCascadingFields(chain consensus.ChainHeaderReader, header *t
return consensus.ErrUnknownAncestor return consensus.ErrUnknownAncestor
} }
if parent.Time+c.config.Period > header.Time { // Verify that the gasUsed is <= gasLimit
if header.GasUsed > header.GasLimit {
return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
}
if !chain.Config().IsLondon(header.Number) {
// Verify BaseFee not present before EIP-1559 fork.
if header.BaseFee != nil {
return fmt.Errorf("invalid baseFee before fork: have %d, want <nil>", header.BaseFee)
}
if err := misc.VerifyGaslimit(parent.GasLimit, header.GasLimit); err != nil {
return err
}
} else if err := misc.VerifyEip1559Header(chain.Config(), parent, header); err != nil {
// Verify the header's EIP-1559 attributes.
return err
}
if parent.Time+c.config.CalculatePeriod(number) > header.Time {
return ErrInvalidTimestamp return ErrInvalidTimestamp
} }
...@@ -549,7 +586,7 @@ func (c *Bor) verifySeal(chain consensus.ChainHeaderReader, header *types.Header ...@@ -549,7 +586,7 @@ func (c *Bor) verifySeal(chain consensus.ChainHeaderReader, header *types.Header
} }
// Resolve the authorization key and check against signers // Resolve the authorization key and check against signers
signer, err := ecrecover(header, c.signatures) signer, err := ecrecover(header, c.signatures, c.config)
if err != nil { if err != nil {
return err return err
} }
...@@ -675,6 +712,11 @@ func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, ...@@ -675,6 +712,11 @@ func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header,
} }
} }
if err = c.changeContractCodeIfNeeded(headerNumber, state); err != nil {
log.Error("Error changing contract code", "error", err)
return
}
// No block rewards in PoA, so the state remains as is and uncles are dropped // No block rewards in PoA, so the state remains as is and uncles are dropped
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
header.UncleHash = types.CalcUncleHash(nil) header.UncleHash = types.CalcUncleHash(nil)
...@@ -684,12 +726,41 @@ func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, ...@@ -684,12 +726,41 @@ func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header,
bc.SetStateSync(stateSyncData) bc.SetStateSync(stateSyncData)
} }
func decodeGenesisAlloc(i interface{}) (core.GenesisAlloc, error) {
var alloc core.GenesisAlloc
b, err := json.Marshal(i)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &alloc); err != nil {
return nil, err
}
return alloc, nil
}
func (c *Bor) changeContractCodeIfNeeded(headerNumber uint64, state *state.StateDB) error {
for blockNumber, genesisAlloc := range c.config.BlockAlloc {
if blockNumber == strconv.FormatUint(headerNumber, 10) {
allocs, err := decodeGenesisAlloc(genesisAlloc)
if err != nil {
return fmt.Errorf("failed to decode genesis alloc: %v", err)
}
for addr, account := range allocs {
log.Info("change contract code", "address", addr)
state.SetCode(addr, account.Code)
}
}
}
return nil
}
// FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, // FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set,
// nor block rewards given, and returns the final block. // nor block rewards given, and returns the final block.
func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) { func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
stateSyncData := []*types.StateSyncData{} stateSyncData := []*types.StateSyncData{}
headerNumber := header.Number.Uint64() headerNumber := header.Number.Uint64()
if headerNumber%c.config.Sprint == 0 { if headerNumber%c.config.Sprint == 0 {
cx := chainContext{Chain: chain, Bor: c} cx := chainContext{Chain: chain, Bor: c}
...@@ -710,6 +781,11 @@ func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *typ ...@@ -710,6 +781,11 @@ func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *typ
} }
} }
if err := c.changeContractCodeIfNeeded(headerNumber, state); err != nil {
log.Error("Error changing contract code", "error", err)
return nil, err
}
// No block rewards in PoA, so the state remains as is and uncles are dropped // No block rewards in PoA, so the state remains as is and uncles are dropped
header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))
header.UncleHash = types.CalcUncleHash(nil) header.UncleHash = types.CalcUncleHash(nil)
...@@ -745,7 +821,7 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result ...@@ -745,7 +821,7 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result
return errUnknownBlock return errUnknownBlock
} }
// For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing)
if c.config.Period == 0 && len(block.Transactions()) == 0 { if c.config.CalculatePeriod(number) == 0 && len(block.Transactions()) == 0 {
log.Info("Sealing paused, waiting for transactions") log.Info("Sealing paused, waiting for transactions")
return nil return nil
} }
...@@ -773,10 +849,10 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result ...@@ -773,10 +849,10 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result
// Sweet, the protocol permits us to sign the block, wait for our time // Sweet, the protocol permits us to sign the block, wait for our time
delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple delay := time.Unix(int64(header.Time), 0).Sub(time.Now()) // nolint: gosimple
// wiggle was already accounted for in header.Time, this is just for logging // wiggle was already accounted for in header.Time, this is just for logging
wiggle := time.Duration(successionNumber) * time.Duration(c.config.BackupMultiplier) * time.Second wiggle := time.Duration(successionNumber) * time.Duration(c.config.CalculateBackupMultiplier(number)) * time.Second
// Sign all the things! // Sign all the things!
sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeBor, BorRLP(header)) sighash, err := signFn(accounts.Account{Address: signer}, accounts.MimetypeBor, BorRLP(header, c.config))
if err != nil { if err != nil {
return err return err
} }
...@@ -808,7 +884,7 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result ...@@ -808,7 +884,7 @@ func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, result
select { select {
case results <- block.WithSeal(header): case results <- block.WithSeal(header):
default: default:
log.Warn("Sealing result was not read by miner", "number", number, "sealhash", SealHash(header)) log.Warn("Sealing result was not read by miner", "number", number, "sealhash", SealHash(header, c.config))
} }
}() }()
return nil return nil
...@@ -827,7 +903,7 @@ func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, par ...@@ -827,7 +903,7 @@ func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, par
// SealHash returns the hash of a block prior to it being sealed. // SealHash returns the hash of a block prior to it being sealed.
func (c *Bor) SealHash(header *types.Header) common.Hash { func (c *Bor) SealHash(header *types.Header) common.Hash {
return SealHash(header) return SealHash(header, c.config)
} }
// APIs implements consensus.Engine, returning the user facing RPC API to allow // APIs implements consensus.Engine, returning the user facing RPC API to allow
...@@ -843,6 +919,7 @@ func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API { ...@@ -843,6 +919,7 @@ func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API {
// Close implements consensus.Engine. It's a noop for bor as there are no background threads. // Close implements consensus.Engine. It's a noop for bor as there are no background threads.
func (c *Bor) Close() error { func (c *Bor) Close() error {
c.HeimdallClient.Close()
return nil return nil
} }
......