block.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright 2021 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package t8ntool
  17. import (
  18. "crypto/ecdsa"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "os"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/hexutil"
  26. "github.com/ethereum/go-ethereum/common/math"
  27. "github.com/ethereum/go-ethereum/consensus/clique"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/urfave/cli/v2"
  34. )
  35. //go:generate go run github.com/fjl/gencodec -type header -field-override headerMarshaling -out gen_header.go
  36. type header struct {
  37. ParentHash common.Hash `json:"parentHash"`
  38. OmmerHash *common.Hash `json:"sha3Uncles"`
  39. Coinbase *common.Address `json:"miner"`
  40. Root common.Hash `json:"stateRoot" gencodec:"required"`
  41. TxHash *common.Hash `json:"transactionsRoot"`
  42. ReceiptHash *common.Hash `json:"receiptsRoot"`
  43. Bloom types.Bloom `json:"logsBloom"`
  44. Difficulty *big.Int `json:"difficulty"`
  45. Number *big.Int `json:"number" gencodec:"required"`
  46. GasLimit uint64 `json:"gasLimit" gencodec:"required"`
  47. GasUsed uint64 `json:"gasUsed"`
  48. Time uint64 `json:"timestamp" gencodec:"required"`
  49. Extra []byte `json:"extraData"`
  50. MixDigest common.Hash `json:"mixHash"`
  51. Nonce *types.BlockNonce `json:"nonce"`
  52. BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"`
  53. }
  54. type headerMarshaling struct {
  55. Difficulty *math.HexOrDecimal256
  56. Number *math.HexOrDecimal256
  57. GasLimit math.HexOrDecimal64
  58. GasUsed math.HexOrDecimal64
  59. Time math.HexOrDecimal64
  60. Extra hexutil.Bytes
  61. BaseFee *math.HexOrDecimal256
  62. }
  63. type bbInput struct {
  64. Header *header `json:"header,omitempty"`
  65. OmmersRlp []string `json:"ommers,omitempty"`
  66. TxRlp string `json:"txs,omitempty"`
  67. Clique *cliqueInput `json:"clique,omitempty"`
  68. Ethash bool `json:"-"`
  69. EthashDir string `json:"-"`
  70. PowMode ethash.Mode `json:"-"`
  71. Txs []*types.Transaction `json:"-"`
  72. Ommers []*types.Header `json:"-"`
  73. }
  74. type cliqueInput struct {
  75. Key *ecdsa.PrivateKey
  76. Voted *common.Address
  77. Authorize *bool
  78. Vanity common.Hash
  79. }
  80. // UnmarshalJSON implements json.Unmarshaler interface.
  81. func (c *cliqueInput) UnmarshalJSON(input []byte) error {
  82. var x struct {
  83. Key *common.Hash `json:"secretKey"`
  84. Voted *common.Address `json:"voted"`
  85. Authorize *bool `json:"authorize"`
  86. Vanity common.Hash `json:"vanity"`
  87. }
  88. if err := json.Unmarshal(input, &x); err != nil {
  89. return err
  90. }
  91. if x.Key == nil {
  92. return errors.New("missing required field 'secretKey' for cliqueInput")
  93. }
  94. if ecdsaKey, err := crypto.ToECDSA(x.Key[:]); err != nil {
  95. return err
  96. } else {
  97. c.Key = ecdsaKey
  98. }
  99. c.Voted = x.Voted
  100. c.Authorize = x.Authorize
  101. c.Vanity = x.Vanity
  102. return nil
  103. }
  104. // ToBlock converts i into a *types.Block
  105. func (i *bbInput) ToBlock() *types.Block {
  106. header := &types.Header{
  107. ParentHash: i.Header.ParentHash,
  108. UncleHash: types.EmptyUncleHash,
  109. Coinbase: common.Address{},
  110. Root: i.Header.Root,
  111. TxHash: types.EmptyRootHash,
  112. ReceiptHash: types.EmptyRootHash,
  113. Bloom: i.Header.Bloom,
  114. Difficulty: common.Big0,
  115. Number: i.Header.Number,
  116. GasLimit: i.Header.GasLimit,
  117. GasUsed: i.Header.GasUsed,
  118. Time: i.Header.Time,
  119. Extra: i.Header.Extra,
  120. MixDigest: i.Header.MixDigest,
  121. BaseFee: i.Header.BaseFee,
  122. }
  123. // Fill optional values.
  124. if i.Header.OmmerHash != nil {
  125. header.UncleHash = *i.Header.OmmerHash
  126. } else if len(i.Ommers) != 0 {
  127. // Calculate the ommer hash if none is provided and there are ommers to hash
  128. header.UncleHash = types.CalcUncleHash(i.Ommers)
  129. }
  130. if i.Header.Coinbase != nil {
  131. header.Coinbase = *i.Header.Coinbase
  132. }
  133. if i.Header.TxHash != nil {
  134. header.TxHash = *i.Header.TxHash
  135. }
  136. if i.Header.ReceiptHash != nil {
  137. header.ReceiptHash = *i.Header.ReceiptHash
  138. }
  139. if i.Header.Nonce != nil {
  140. header.Nonce = *i.Header.Nonce
  141. }
  142. if header.Difficulty != nil {
  143. header.Difficulty = i.Header.Difficulty
  144. }
  145. return types.NewBlockWithHeader(header).WithBody(i.Txs, i.Ommers)
  146. }
  147. // SealBlock seals the given block using the configured engine.
  148. func (i *bbInput) SealBlock(block *types.Block) (*types.Block, error) {
  149. switch {
  150. case i.Ethash:
  151. return i.sealEthash(block)
  152. case i.Clique != nil:
  153. return i.sealClique(block)
  154. default:
  155. return block, nil
  156. }
  157. }
  158. // sealEthash seals the given block using ethash.
  159. func (i *bbInput) sealEthash(block *types.Block) (*types.Block, error) {
  160. if i.Header.Nonce != nil {
  161. return nil, NewError(ErrorConfig, fmt.Errorf("sealing with ethash will overwrite provided nonce"))
  162. }
  163. ethashConfig := ethash.Config{
  164. PowMode: i.PowMode,
  165. DatasetDir: i.EthashDir,
  166. CacheDir: i.EthashDir,
  167. DatasetsInMem: 1,
  168. DatasetsOnDisk: 2,
  169. CachesInMem: 2,
  170. CachesOnDisk: 3,
  171. }
  172. engine := ethash.New(ethashConfig, nil, true)
  173. defer engine.Close()
  174. // Use a buffered chan for results.
  175. // If the testmode is used, the sealer will return quickly, and complain
  176. // "Sealing result is not read by miner" if it cannot write the result.
  177. results := make(chan *types.Block, 1)
  178. if err := engine.Seal(nil, block, results, nil); err != nil {
  179. panic(fmt.Sprintf("failed to seal block: %v", err))
  180. }
  181. found := <-results
  182. return block.WithSeal(found.Header()), nil
  183. }
  184. // sealClique seals the given block using clique.
  185. func (i *bbInput) sealClique(block *types.Block) (*types.Block, error) {
  186. // If any clique value overwrites an explicit header value, fail
  187. // to avoid silently building a block with unexpected values.
  188. if i.Header.Extra != nil {
  189. return nil, NewError(ErrorConfig, fmt.Errorf("sealing with clique will overwrite provided extra data"))
  190. }
  191. header := block.Header()
  192. if i.Clique.Voted != nil {
  193. if i.Header.Coinbase != nil {
  194. return nil, NewError(ErrorConfig, fmt.Errorf("sealing with clique and voting will overwrite provided coinbase"))
  195. }
  196. header.Coinbase = *i.Clique.Voted
  197. }
  198. if i.Clique.Authorize != nil {
  199. if i.Header.Nonce != nil {
  200. return nil, NewError(ErrorConfig, fmt.Errorf("sealing with clique and voting will overwrite provided nonce"))
  201. }
  202. if *i.Clique.Authorize {
  203. header.Nonce = [8]byte{}
  204. } else {
  205. header.Nonce = [8]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  206. }
  207. }
  208. // Extra is fixed 32 byte vanity and 65 byte signature
  209. header.Extra = make([]byte, 32+65)
  210. copy(header.Extra[0:32], i.Clique.Vanity.Bytes()[:])
  211. // Sign the seal hash and fill in the rest of the extra data
  212. h := clique.SealHash(header)
  213. sighash, err := crypto.Sign(h[:], i.Clique.Key)
  214. if err != nil {
  215. return nil, err
  216. }
  217. copy(header.Extra[32:], sighash)
  218. block = block.WithSeal(header)
  219. return block, nil
  220. }
  221. // BuildBlock constructs a block from the given inputs.
  222. func BuildBlock(ctx *cli.Context) error {
  223. // Configure the go-ethereum logger
  224. glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
  225. glogger.Verbosity(log.Lvl(ctx.Int(VerbosityFlag.Name)))
  226. log.Root().SetHandler(glogger)
  227. baseDir, err := createBasedir(ctx)
  228. if err != nil {
  229. return NewError(ErrorIO, fmt.Errorf("failed creating output basedir: %v", err))
  230. }
  231. inputData, err := readInput(ctx)
  232. if err != nil {
  233. return err
  234. }
  235. block := inputData.ToBlock()
  236. block, err = inputData.SealBlock(block)
  237. if err != nil {
  238. return err
  239. }
  240. return dispatchBlock(ctx, baseDir, block)
  241. }
  242. func readInput(ctx *cli.Context) (*bbInput, error) {
  243. var (
  244. headerStr = ctx.String(InputHeaderFlag.Name)
  245. ommersStr = ctx.String(InputOmmersFlag.Name)
  246. txsStr = ctx.String(InputTxsRlpFlag.Name)
  247. cliqueStr = ctx.String(SealCliqueFlag.Name)
  248. ethashOn = ctx.Bool(SealEthashFlag.Name)
  249. ethashDir = ctx.String(SealEthashDirFlag.Name)
  250. ethashMode = ctx.String(SealEthashModeFlag.Name)
  251. inputData = &bbInput{}
  252. )
  253. if ethashOn && cliqueStr != "" {
  254. return nil, NewError(ErrorConfig, fmt.Errorf("both ethash and clique sealing specified, only one may be chosen"))
  255. }
  256. if ethashOn {
  257. inputData.Ethash = ethashOn
  258. inputData.EthashDir = ethashDir
  259. switch ethashMode {
  260. case "normal":
  261. inputData.PowMode = ethash.ModeNormal
  262. case "test":
  263. inputData.PowMode = ethash.ModeTest
  264. case "fake":
  265. inputData.PowMode = ethash.ModeFake
  266. default:
  267. return nil, NewError(ErrorConfig, fmt.Errorf("unknown pow mode: %s, supported modes: test, fake, normal", ethashMode))
  268. }
  269. }
  270. if headerStr == stdinSelector || ommersStr == stdinSelector || txsStr == stdinSelector || cliqueStr == stdinSelector {
  271. decoder := json.NewDecoder(os.Stdin)
  272. if err := decoder.Decode(inputData); err != nil {
  273. return nil, NewError(ErrorJson, fmt.Errorf("failed unmarshaling stdin: %v", err))
  274. }
  275. }
  276. if cliqueStr != stdinSelector && cliqueStr != "" {
  277. var clique cliqueInput
  278. if err := readFile(cliqueStr, "clique", &clique); err != nil {
  279. return nil, err
  280. }
  281. inputData.Clique = &clique
  282. }
  283. if headerStr != stdinSelector {
  284. var env header
  285. if err := readFile(headerStr, "header", &env); err != nil {
  286. return nil, err
  287. }
  288. inputData.Header = &env
  289. }
  290. if ommersStr != stdinSelector && ommersStr != "" {
  291. var ommers []string
  292. if err := readFile(ommersStr, "ommers", &ommers); err != nil {
  293. return nil, err
  294. }
  295. inputData.OmmersRlp = ommers
  296. }
  297. if txsStr != stdinSelector {
  298. var txs string
  299. if err := readFile(txsStr, "txs", &txs); err != nil {
  300. return nil, err
  301. }
  302. inputData.TxRlp = txs
  303. }
  304. // Deserialize rlp txs and ommers
  305. var (
  306. ommers = []*types.Header{}
  307. txs = []*types.Transaction{}
  308. )
  309. if inputData.TxRlp != "" {
  310. if err := rlp.DecodeBytes(common.FromHex(inputData.TxRlp), &txs); err != nil {
  311. return nil, NewError(ErrorRlp, fmt.Errorf("unable to decode transaction from rlp data: %v", err))
  312. }
  313. inputData.Txs = txs
  314. }
  315. for _, str := range inputData.OmmersRlp {
  316. type extblock struct {
  317. Header *types.Header
  318. Txs []*types.Transaction
  319. Ommers []*types.Header
  320. }
  321. var ommer *extblock
  322. if err := rlp.DecodeBytes(common.FromHex(str), &ommer); err != nil {
  323. return nil, NewError(ErrorRlp, fmt.Errorf("unable to decode ommer from rlp data: %v", err))
  324. }
  325. ommers = append(ommers, ommer.Header)
  326. }
  327. inputData.Ommers = ommers
  328. return inputData, nil
  329. }
  330. // dispatchOutput writes the output data to either stderr or stdout, or to the specified
  331. // files
  332. func dispatchBlock(ctx *cli.Context, baseDir string, block *types.Block) error {
  333. raw, _ := rlp.EncodeToBytes(block)
  334. type blockInfo struct {
  335. Rlp hexutil.Bytes `json:"rlp"`
  336. Hash common.Hash `json:"hash"`
  337. }
  338. var enc blockInfo
  339. enc.Rlp = raw
  340. enc.Hash = block.Hash()
  341. b, err := json.MarshalIndent(enc, "", " ")
  342. if err != nil {
  343. return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err))
  344. }
  345. switch dest := ctx.String(OutputBlockFlag.Name); dest {
  346. case "stdout":
  347. os.Stdout.Write(b)
  348. os.Stdout.WriteString("\n")
  349. case "stderr":
  350. os.Stderr.Write(b)
  351. os.Stderr.WriteString("\n")
  352. default:
  353. if err := saveFile(baseDir, dest, enc); err != nil {
  354. return err
  355. }
  356. }
  357. return nil
  358. }