mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-29 16:13:47 +00:00
* ethdb/pebble: fix nil callbacks (#26650) * eth/downloader: fix timeout resurrection panic (#26652) * common/prque, eth/downloader: fix timeout resurrection panic * common/prque: revert -1 hack for les, temporaryly! * core/state, trie: remove unused error-return from trie Commit operation (#26641) * go.mod: update pebble to latest master (#26654) * core/vm: set tracer-observable `value` of a delegatecall to match parent `value` (#26632) This is a breaking change in the tracing hooks API as well as semantics of the callTracer: - CaptureEnter hook provided a nil value argument in case of DELEGATECALL. However to stay consistent with how delegate calls behave in EVM this hook is changed to pass in the value of the parent call. - callTracer will return parent call's value for DELEGATECALL frames. --------- Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> * ethdb: add benchmark test suite (#26659) * params: schedule shanghai fork on sepolia (#26662) * params: schedule shanghai fork on sepolia * params: u64 -> newUint64 * eth/filters: avoid block body retrieval when no matching logs (#25199) Logs stored on disk have minimal information. Contextual information such as block number, index of log in block, index of transaction in block are filled in upon request. We can fill in all these fields only having the block header and list of receipts. But determining the transaction hash of a log requires the block body. The goal of this PR is postponing this retrieval until we are sure we the transaction hash. It happens often that the header bloom filter signals there might be matches in a block, but after actually checking them reveals the logs do not match. We want to avoid fetching the body in this case. Note that this changes the semantics of Backend.GetLogs. Downstream callers of GetLogs now assume log context fields have not been derived, and need to call DeriveFields on the logs if necessary. * eth/tracers: more fork overrides in traceBlockToFile (#26655) This change allows all post-Berlin forks to be specified as overrides for futureForkBlock in the config parameter for traceBlockToFile. * tests/fuzzers: supply gnark multiexp config, fixes #26669 (#26670) This change fixes a fuzzer which broke when we updated the gnark dependency earlier. * cmd/devp2p: reduce output of node crawler (#26674) Our discovery crawler spits out a huge amount of logs, most of which is pretty non-interesting. This change moves the very verbose output to Debug, and adds a 8-second status log message giving the general idea about what's going on. * params: update mainnet + rinkeby CHT (#26677) This change updates the CHT entries for mainnet and rinkeby * eth/filters: replace atomic pointer with value (#26689) * eth/filters: replace atomic.Pointer * fix * improve Co-authored-by: Martin Holst Swende <martin@swende.se> --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * p2p/dnsdisc: fix tests with Go 1.20 (#26690) * eth/catalyst: return error if withdrawals are nil post-shanghai (#26691) Spec: https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md#request * ethdb/pebble: Fix `MemTableStopWritesThreshold` (#26692) MemTableStopWritesThreshold was set to the max size of all memtables before blocking writing but should be set to the max number of memtables. This is documented [here](https://github.com/cockroachdb/pebble/blob/master/options.go#L738-L742). * eth/downloader: handle missing withdrawals if empty list is expected (#26675) This PR relaxes the block body ingress handling a bit: if block body withdrawals are missing (but expected to be empty), the body withdrawals are set to 'empty list' before being passed to upper layers. This fixes an issue where a block passed from EthereumJS to geth was deemed invalid. * params: go-ethereum v1.11.0 stable * params: begin v1.11.1 release cycle * travis, build: update Go to 1.20.1 (#26653) travis, build: update Go to 1.20 * core: check genesis state presence by disk read (#26703) * core, eth/downloader: make body validation more strict (#26704) * eth/downloader: fix empty-body case in queue fetchresult (#26707) * eth/downloader: fix typo (#26716) * all: remove deprecated uses of math.rand (#26710) This PR is a (superior) alternative to https://github.com/ethereum/go-ethereum/pull/26708, it handles deprecation, primarily two specific cases. `rand.Seed` is typically used in two ways - `rand.Seed(time.Now().UnixNano())` -- we seed it, just to be sure to get some random, and not always get the same thing on every run. This is not needed, with global seeding, so those are just removed. - `rand.Seed(1)` this is typically done to ensure we have a stable test. If we rely on this, we need to fix up the tests to use a deterministic prng-source. A few occurrences like this has been replaced with a proper custom source. `rand.Read` has been replaced by `crypto/rand`.`Read` in this PR. * params: go-ethereum v1.11.1 stable * params: begin v1.11.2 release cycle * eth/catalyst: send INVALID instead of INVALID_BLOCK_HASH (#26696) This change will break one hive test, but pass another and it will be the better way going forward * ci: disable coverage reporting in appveyor and travis * eth/catalyst: request too large error (#26722) The method `GetPayloadBodiesByRangeV1` now returns "-38004: Too large request" error if the requested range is too large, according to spec Co-authored-by: Martin Holst Swende <martin@swende.se> * core/trie: remove trie tracer (#26665) This PR contains a small portion of the full pbss PR, namely Remove the tracer from trie (and comitter), and instead using an accessList. Related changes to the Nodeset. --------- Co-authored-by: Gary Rong <garyrong0905@gmail.com> * rpc: fix unmarshaling of null result in CallContext (#26723) The change fixes unmarshaling of JSON null results into json.RawMessage. --------- Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com> Co-authored-by: Jason Yuan <jason.yuan869@gmail.com> * build: ship bootstrapper Go along with builder for PPA (#26731) * build: fix setting env var, temp early exit * build: fix gobootstrap path for the PPA * build: add some PPA debug logs, sigh * internal/build: revert raising the chunk size for PPA * build: yet another weird PPA fix * build: fix (finaly?) the PPA env vars for Go bootstrapping * build: fix Go 1.19.0 bootstrapper issues on 386 PPA * build: enable Lunar Lobster PPA builds * Revert "core/trie: remove trie tracer (#26665)" (#26732) This reverts commit7c749c947a. * cmd/geth: clarify dumpconfig options (#26729) Clarifies the documentation around dumpconfi Signed-off-by: Sungwoo Kim <git@sung-woo.kim> * core, eth: merge snap-sync chain download progress logs (#26676) * core: fix accessor mismatch for genesis state (#26747) * core/rawdb: expose chain freezer constructor without internals (#26748) * all: use unified emptyRootHash and emptyCodeHash (#26718) The EmptyRootHash and EmptyCodeHash are defined everywhere in the codebase, this PR replaces all of them with unified one defined in core/types package, and also defines constants for TxRoot, WithdrawalsRoot and UncleRoot * eth/filters: fix a breaking change and return rpctransaction (#26757) * eth/filters: fix a breaking change and return rpctransaction * eth/filters: fix test cases --------- Co-authored-by: Catror <me@catror.com> * common/math: allow HexOrDecimal to accept unquoted decimals too (#26758) * params: release Geth v1.11.2 * params: begin v.1.11.3 release cycle * log: improve documentation (#26753) Add usage examples * core/rawdb, node: use standalone flock dependency (#26633) * eth: use the last announced finalized block as the sync ancient limit (#26685) * cmd/devp2p: faster crawling + less verbose dns updates (#26697) This improves the speed of DHT crawling by using concurrent requests. It also removes logging of individual DNS updates. * eth/tracers: add native flatCallTracer (aka parity style tracer) (#26377) Adds support for a native call tracer with the Parity format, which outputs call frames in a flat array. This tracer accepts the following options: - `convertParityErrors: true` will convert error messages to match those of Parity - `includePrecompiles: true` will report all calls to precompiles. The default matches Parity's behavior where CALL and STATICCALLs to precompiles are excluded Incompatibilities with Parity include: - Parity removes the result object in case of failure. This behavior is maintained with the exception of reverts. Revert output usually contains useful information, i.e. Solidity revert reason. - The `gasUsed` field accounts for intrinsic gas (e.g. 21000 for simple transfers) and refunds unlike Parity - Block rewards are not reported Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> * core: improve withdrawal index assignment in GenerateChain (#26756) This fixes an issue where the withdrawal index was not calculated correctly for multiple withdrawals in a single block. Co-authored-by: Gary Rong <garyrong0905@gmail.com> Co-authored-by: Felix Lange <fjl@twurst.com> * ethdb/pebble: fix range compaction (#26771) * ethdb/pebble: fix range compaction * ethdb/pebble: add comment * ethdb/pebble: fix max memorytable size (#26776) * ethclient: include withdrawals in ethclient block responses (#26778) * include withdrawals in ethclient responses * omit empty withdrawals array in json serialization * all: change chain head markers from block to header (#26777) * core/rawdb, ethdb/pebble: disable pebble on openbsd (#26801) * core: fix a merge fault (#26802) * README, go.mod, event, internal/version: bump min Go to 1.19 (#26803) * travi: remove strange leftover Go version * core, params: schedule Shanghai on goerli (#26795) * core: params: schedule Shanghai on goerli * core/forkid: fix comment * eth: remove admin.peers[i].eth.head and difficulty (#26804) * core/types: add EffectiveGasPrice in Receipt (#26713) This change adds a struct field EffectiveGasPrice in types.Receipt. The field is present in RPC responses, but not in the Go struct, and thus can't easily be accessed via ethclient. Co-authored-by: PulsarAI <dev@pulsar-systems.fi> * core, eth/catalyst: fix race conditions in tests (#26790) Fixes a race in TestNewPayloadOnInvalidTerminalBlock where setting the TTD raced with the miner. Solution: set the TTD on the blockchain config not the genesis config. Also fixes a race in CopyHeader which resulted in race reports all over the place. * metrics: improve accuracy of CPU gauges (#26793) This PR changes metrics collection to actually measure the time interval between collections, rather than assume 3 seconds. I did some ad hoc profiling, and on slower hardware (eg, my Raspberry Pi 4) I routinely saw intervals between 3.3 - 3.5 seconds, with some being as high as 4.5 seconds. This will generally cause the CPU gauge readings to be too high, and in some cases can cause impossibly large values for the CPU load metrics (eg. greater than 400 for a 4 core CPU). --------- Co-authored-by: Felix Lange <fjl@twurst.com> * ethclient: fix panic when requesting missing blocks (#26817) This fixes a regression introduced by #26723. Fixes #26816. * core, miner: revert block gas counter in case of invalid transaction (#26799) This change fixes a flaw where, in certain scenarios, the block sealer did not accurately reset the remaining gas after failing to include an invalid transaction. Fixes #26791 * internal/ethapi: add tests for transaction types JSON marshal/unmarshal (#26667) Checks that Transaction.MarshalJSON and newRPCTransaction JSON output can be parsed by Transaction.UnmarshalJSON --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * cmd/evm: correct `alloc` for `t8n` testdata (#26822) Fixes a minor error in the testdata * eth/tracers/native: set created address to nil in case of failure (#26779) Fixes #26073 * accounts/usbwallet: mitigate ledger app chunking issue (#26773) This PR mitigates an issue with Ledger's on-device RLP deserialization, see https://github.com/LedgerHQ/app-ethereum/issues/409 Ledger's RLP deserialization code does not validate the length of the RLP list received, and it may prematurely enter the signing flow when a APDU chunk boundary falls immediately before the EIP-155 chain_id when deserializing a transaction. Since the chain_id is uninitialized, it is 0 during this signing flow. This may cause the user to accidentally sign the transaction with chain_id = 0. That signature would be returned from the device 1 packet earlier than expected by the communication loop. The device blocks the second-to-last packet waiting for the signer flow, and then errors on the successive packet (which contains the chain_id, zeroed r, and zeroed s) Since the signature's early arrival causes successive errors during the communication process, geth does not parse the improper signature produced by the device, and therefore no improperly-signed transaction can be created. User funds are not at risk. We mitigate by selecting the highest chunk size that leaves at least 4 bytes in the final chunk. * beacon/engine: don't omit empty withdrawals in ExecutionPayloadBodies (#26698) This ensures the "withdrawals" field will always be present in responses to getPayloadBodiesByRangeV1 and getPayloadBodiesByHashV1. --------- Co-authored-by: Felix Lange <fjl@twurst.com> * build: update to go 1.20.2 (#26824) * params: go-ethereum v1.11.3 stable * params: begin v1.11.4 release cycle * core/rawdb: find smallest block stored in key-value store when chain gapped (#26719) This change prints out more information about the problem, in the case where geth detects a gap between leveldb and ancients, so we can determine more exactly where the gap is (what the first missing is). Also prints out more metadata. --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * signer/core: accept all solidity primitive types for EIP-712 signing (#26770) Accept all primitive types in Solidity for EIP-712 from intN, uintN, intN[], uintN[] for N as 0 to 256 in multiples of 8 --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * params: remove EF azure bootnodes (#26828) * core/vm: use golang native big.Int (#26834) reverts #26021, to use the upstream bigint instead. * core/vm: fix typo in comment (#26838) fixes eip 220 -> 2200 * core/forkid: fix issue in validation test (#26544) This changes the test to match the comment description. Using timestampedConfig in this test case is incorrect, the comment says 'local is at Gray Glacier' and isn't aware of more forks. * cmd/evm: update readmes for the tests (#26841) * core, core/types: plain Message struct (#25977) Here, the core.Message interface turns into a plain struct and types.Message gets removed. This is a breaking change to packages core and core/types. While we do not promise API stability for package core, we do for core/types. An exception can be made for types.Message, since it doesn't have any purpose apart from invoking the state transition in package core. types.Message was also marked deprecated by the same commit it got added in,4dca5d4db7(November 2016). The core.Message interface was added in December 2014, in commitdb494170dc, for the purpose of 'testing' state transitions. It's the same change that made transaction struct fields private. Before that, the state transition used *types.Transaction directly. Over time, multiple implementations of the interface accrued across different packages, since constructing a Message is required whenever one wants to invoke the state transition. These implementations all looked very similar, a struct with private fields exposing the fields as accessor methods. By changing Message into a struct with public fields we can remove all these useless interface implementations. It will also hopefully simplify future changes to the type with less updates to apply across all of go-ethereum when a field is added to Message. --------- Co-authored-by: Felix Lange <fjl@twurst.com> * travis: only build PPAs nightly, not on every push, too heavy (#26846) * p2p: small comment typo (#26850) Update server.go * core: add Timestamp method in BlockGen (#26844) Since forks are now scheduled by block time, it can be necessary to check the timestamp of a block while generating transactions. * core/txpool: implement additional DoS defenses (#26648) This adds two new rules to the transaction pool: - A future transaction can not evict a pending transaction. - A transaction can not overspend available funds of a sender. --- Co-authored-by: dwn1998 <42262393+dwn1998@users.noreply.github.com> Co-authored-by: Martin Holst Swende <martin@swende.se> * params: go-ethereum v1.11.4 stable * params: begin v1.11.5 release cycle * tests: define `MuirGlacier` fork (#26856) add muir glacier to t8n * code/vm: fix comment typo (#26865) it should be constantinople rather than contantinople * core: minor code refactor (#26852) * core: refactor code * core: drop it from this anonymous goroutine func * core/txpool: use priceList.Put instead of heap.Push (#26863) Minor refactor to use the 'intended' accessor * eth: return error if 'safe' or 'finalized' tag used pre-merge (#26862) Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: Felix Lange <fjl@twurst.com> * .travis.yml: reenable PPA build on tag push (#26873) * core/state, trie: port changes from PBSS (#26763) * p2p/discover: pass invalid discv5 packets to Unhandled channel (#26699) This makes it possible to run another protocol alongside discv5, by reading unhandled packets from the channel. * all: update links in documentation (#26882) Co-authored-by: Stephen Flynn <stephen.flynn@gapac.com> * Increase websocket frame size (from erigon rpc client) (#26883) This increases the maximum allowed message size to 32MB. Originally submitted at https://github.com/ledgerwatch/erigon/pull/2739 example block failure: https://etherscan.io/tx/0x1317d973a55cedf9b0f2df6ea48e8077dd176f5444a3423368a46d6e4db89982#internal * cmd/devp2p, cmd/geth: add version in --help output (#26895) Not sure why this was removed, it's pretty useful to see the version also in --help. * core: show db error-info in case of mismatched hash root (#26870) When a database failure occurs, bubble it up a into statedb, and report it in suitable places, such as during a 'bad block' report. * consensus: improve consensus engine definition (#26871) Makes clear the distinction between Finalize and FinalizedAndAssemble: - In Finalize function, a series of state operations are applied according to consensus rules. The statedb is mutated and the root hash can be checked and compared afterwards. This function should be used in block processing(receive afrom network and apply it locally) but not block generation. - In FinalizeAndAssemble function, after applying state mutations, the block is also to be assembled with the latest state root computed, updating the header. This function should be used in block generation only. * eth/catalyst: increase update consensus timeout (#26840) Increases the time between consensus updates that we give the CL before we start warning the user. * internal/ethapi: avoid int overflow in GetTransactionReceipt (#26911) * trie, accounts/abi: add error-checks (#26914) * rlp: support for uint256 (#26898) This adds built-in support in package rlp for encoding, decoding and generating code dealing with uint256.Int. --------- Co-authored-by: Felix Lange <fjl@twurst.com> * eth: fix output file permissions in admin_exportChain (#26912) * api: Use 0700 file permissions for ExportChain * change perm to 0644 * Update api.go --------- Co-authored-by: Felix Lange <fjl@twurst.com> * trie: reduce unit test time (#26918) * core/txpool: use atomic int added in go1.19 (#26913) Makes use of atomic.Uint64 instead of atomic by pointer * params: schedule shanghai fork on mainnet (#26908) Schedules the shanghai hardfork on timestamp 1681338455 as discussed on ACDE 157: https://github.com/ethereum/execution-specs/pull/727 * core/txpool: allow future local transactions (#26930) Local transactions should not be subject to the "future shouldn't churn pending txs" rule * params: go-ethereum v1.11.5 stable * params: begin v1.11.6 release cycle * build: allow building nightly archives via cron jobs (#26938) * log: add special casing of uint256 into the logger (#26936) * core/rawdb: use atomic int added in go1.19 (#26935) * core/vm: expose jumptable constructors (#26880) When interacting with geth as a library to e.g. produce state tests, it is desirable to obtain the consensus-correct jumptable definition for a given fork. This changes adds accessors so the instructionset can be obtained and characteristics about opcodes can be inspected. * eth/catalyst: fix races (#26950) * core/rawdb: update freezertable read meter (#26946) The meter for "for measuring the effective amount of data read" within the freezertable was never updated. This change remedies that. --------- Signed-off-by: jsvisa <delweng@gmail.com> * cmd/evm, tests: record preimages if dump is expected (#26955) With #25287 we made it so that preimages were not recorded by default. This had the side effect that the evm command is no longer able to dump state since it does a preimage lookup to determine the address represented by a key. This change enables the recording of preimages when the dump command is given. * core/state: add account address to Trie slot accessors (#26934) This changes the Trie interface to add the plain account address as a parameter to all storage-related methods. After the introduction of the TryAccount* functions, TryGet, TryUpdate and TryDelete are now only meant to read an account's storage. In their current form, they assume that an account storage is stored in a separate trie, and that the hashing of the slot is independent of its account's address. The proposed structure for a stateless storage breaks these two assumptions: the hashing of a slot key requires the address and all slots and accounts are stored in a single trie. This PR therefore adds an address parameter to the interface. It is ignored in the MPT version, so this change has no functional impact, however it will reduce the diff size when merging verkle trees. * metrics: add cpu counters (#26796) This PR adds counter metrics for the CPU system and the Geth process. Currently the only metrics available for these items are gauges. Gauges are fine when the consumer scrapes metrics data at the same interval as Geth produces new values (every 3 seconds), but it is likely that most consumers will not scrape that often. Intervals of 10, 15, or maybe even 30 seconds are probably more common. So the problem is, how does the consumer estimate what the CPU was doing in between scrapes. With a counter, it's easy ... you just subtract two successive values and divide by the time to get a nice, accurate average. But with a gauge, you can't do that. A gauge reading is an instantaneous picture of what was happening at that moment, but it gives you no idea about what was going on between scrapes. Taking an average of values is meaningless. * metrics/influxdb: use smaller dependency and reuse code between v1 and v2 reporters (#26963) This change switches to use the smaller influxdata/influxdb1-client package instead of depending on the whole infuxdb package. The new smaller client is very similar to the influxdb-v2 client, which made it possible to refactor the two reporters to reuse code a lot more. * eth/gasprice: change feehistory input type from int to uint64 (#26922) Change input param type from int to uint64 * go.mod: update golang.org/x/tools (#26960) * rlp/rlpgen: print want/expect output string if mismatch (#26932) Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> * ethclient: ensure returned subscription is nil on error (#26976) * core/state, trie: remove Try prefix in Trie accessors (#26975) This change renames StateTrie methods to remove the Try* prefix. We added the Trie methods with prefix 'Try' a long time ago, working around the problem that most existing methods of Trie did not return the database error. This weird naming convention has persisted until now. Co-authored-by: Gary Rong <garyrong0905@gmail.com> * metrics/librato: ensure resp.body closed (#26969) This change ensures that we call Close on a http response body, in various places in the source code (mostly tests) * core/vm: use atomic.Bool (#26951) Make use of new atomic types --------- Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: Martin Holst Swende <martin@swende.se> * core/bloombits: use atomic type (#26993) * core/state: use atomic.Bool (#26992) * graphql: fix data races (#26965) Fixes multiple data races caused by the fact that resolving fields are done concurrently by the graphql library. It also enforces caching at the stateobject level for account fields. * eth/tracers/native: prevent panic for LOG edge-cases (#26848) This PR fixes OOM panic in the callTracer as well as panicing on opcode validation errors (e.g. stack underflow) in callTracer and prestateTracer. Co-authored-by: Martin Holst Swende <martin@swende.se> * internal/debug: add log.logfmt flag to set logging to use logfmt (#26970) * docs: update outdated DeriveSha docs comment (#26968) * remove @gballet as a GraphQL codeowner (#27012) * core: use atomic type (#27011) * graphql: revert storage access regression (#27007) * cmd/geth: Add `--log.format` cli param (#27001) Removes the new --log.logfmt directive and hides --log.json, replacing both with log.format=(json|logfmt|terminal). The hidden log.json option is still respected if log.format is not specified for backwards compatibility. Co-authored-by: Martin Holst Swende <martin@swende.se> * ethdb/pebble: use atomic type (#27014) * common: fix json marshaller MixedcaseAddress (#26998) Fix the json marshaller of MixedcaseAddress * eth/catalyst: improve consensus heartbeat (#26896) improve the heartbeat function that is no longer suitable in the current situation Co-authored-by: “openex27” <“openexkevin@gmail.com”> * miner: use atomic type (#27013) Use the new typed atomics in the miner package * accounts/abi/bind: handle UnpackLog with zero topics (#26920) Adds error handling for the case that UnpackLog or UnpackLogIntoMap is called with a log that has zero topics. --------- Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> * cmd/evm: use correct parent number for t8n base fee calculation (#27032) Currently the t8n tool uses the same block number for the current block and its parent while calculating the base fee. This causes incorrect base fee calculation for the london fork block. This commit sets the parent block number to be one less than the current block number * go.mod : update snappy (#27027) * common: delete MakeName (#27023) common,p2p: remove unused function MakeName * cmd/geth: enable log rotation (#26843) This change enables log rotation, which can be activated using the flag --log.rotate. Additional parameters that can be given are: - log.maxsize to set maximum size before files are rotated, - log.maxbackups to set how many files are retailed, - log.maxage to configure max age of rotated files, - log.compress whether to compress rotated files The way to configure location of the logfile(s) is left unchanged, via the `log.logfile` parameter. --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * cmd, miner, signer: avoid panic if keystore is not available (#27039) * cmd, miner, singer: avoid panic if keystore is not available * cmd/geth: print warning instead of panic * test/fuzzers: fuzz rlp handling of big.Int and uint256.Int (#26917) test/fuzzers: fuzz rlp handling of big.Lnt and uint256.Int * core/txpool: move some validation to outside of mutex (#27006) Currently, most of transaction validation while holding the txpool mutex: one exception being an early-on signature check. This PR changes that, so that we do all non-stateful checks before we entering the mutex area. This means they can be performed in parallel, and to enable that, certain fields have been made atomic bools and uint64. * eth/downloader: use atomic types (#27030) * eth/downloader: use atomic type * Update eth/downloader/downloader_test.go Co-authored-by: Martin Holst Swende <martin@swende.se> * Update eth/downloader/downloader_test.go Co-authored-by: Martin Holst Swende <martin@swende.se> --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * core/vm: clarify comment (#27045) * consensus, core/typer: add 4844 excessDataGas to header, tie it to Cancun (#27046) * consensus/misc, params: add EIP-4844 blobfee conversions (#27041) * consensus/misc, params: add EIP-4844 blobfee conversions * consensus/misc: pull in fakeExponential test cases * consensus/misc: reuse bigints * consensus/misc: nit renames, additional larger testcase --------- Co-authored-by: Roberto Bayardo <bayardo@alum.mit.edu> Co-authored-by: Martin Holst Swende <martin@swende.se> * eth/tracers: report correct gasLimit in call tracers (#27029) This includes a semantic change to the `callTracer` as well as `flatCallTracer`. The value of field `gas` in the **first** call frame will change as follows: - It previously contained gas available after initial deductions (i.e. tx costs) - It will now contain the full tx gasLimit value Signed-off-by: jsvisa <delweng@gmail.com> * all: remove debug-field from vm config (#27048) This PR removes the Debug field from vmconfig, making it so that if a tracer is set, debug=true is implied. --------- Co-authored-by: 0xTylerHolmes <tyler@ethereum.org> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> * metrics: make gauge_float64 and counter_float64 lock free (#27025) Makes the float-gauges lock-free name old time/op new time/op delta CounterFloat64Parallel-8 1.45µs ±10% 0.85µs ± 6% -41.65% (p=0.008 n=5+5) --------- Co-authored-by: Exca-DK <dev@DESKTOP-RI45P4J.localdomain> Co-authored-by: Martin Holst Swende <martin@swende.se> * eth/tracers: use atomic type (#27031) Use the new atomic types in package eth/tracers --------- Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> * build: upgrade -dlgo version to Go 1.20.3 * core/txpool: disallow future churn by remote txs (#26907) Prior to this change, it was possible that transactions are erroneously deemed as 'future' although they are in fact 'pending', causing them to be dropped due to 'future' not being allowed to replace 'pending'. This change fixes that, by doing a more in-depth inspection of the queue. * core, miner: drop transactions from the same sender when error occurs (#27038) This PR unifies the error handling in miner. Whenever an error occur while applying a transaction, the transaction should be regarded as invalid and all following transactions from the same sender not executable because of the nonce restriction. The only exception is the `nonceTooLow` error which is handled separately. * params: new sepolia bootnodes (#27099) New sepolia bootnodes managed by EF devops * cmd/devp2p: fix erroneous log output in crawler (#27089) cmd/devp2p: fix log of ignored recent nodes counter * signer/core: rename testdata files (#27063) Sets a meaningful name on test-files * core: fix comment to reflect function name (#27070) * params: remove `EIP150Hash` from chainconfig (#27087) The EIP150Hash was an idea where, after the fork, we hardcoded the forked hash as an extra defensive mechanism. It wasn't really used, since forks weren't contentious and for all the various testnets and private networks it's been a hassle to have around. This change removes that config field. --------- Signed-off-by: jsvisa <delweng@gmail.com> * p2p: access embedded fields of Server directly (#27078) * consensus/ethash: use atomic type (#27068) * cmd/devp2p: make crawler-route53-updater less verbose (#27116) Follow-up to #26697, makes the crawler less verbose on route53-based scenarios. It also changes the loglevel from debug to info on Updates, which are typically the root, and can be interesting to see. * cmd/geth: rename --vmodule to --log.vmodule (#27071) renames `--vmodule` to `--log.vmodule`, and prints a warning if the old form is used. * core/vm: order opcodes properly (#27113) * metrics: use atomic type (#27121) * all: refactor trie API (#26995) In this PR, all TryXXX(e.g. TryGet) APIs of trie are renamed to XXX(e.g. Get) with an error returned. The original XXX(e.g. Get) APIs are renamed to MustXXX(e.g. MustGet) and does not return any error -- they print a log output. A future PR will change the behaviour to panic on errorrs. * params: go-ethereum v1.11.6 stable * dev: chg: regression changes for bor after merge * dev: chg: more regression changes for bor after merge * dev: chg: txpool_test regression changes after merge * dev: chg: gomock re-generate mocks for backend interface * dev: chg: regression changes after develop is merged into upstream-merge * dev: chg: further fixes merging develop into upstream-merge * dev: chg: apply changes to NewParallelBlockChain * dev: chg: solve some TODOs * dev: fix: CreateConsensusEngine for new ethereum objects * dev: fix: NewParallelBlockChain using Genesis * dev: fix: build ci.go * dev: fix: thelper and tparallel lint * dev: fix: http related and nilnil lint errors * dev: fix: ineffassign lint errors * dev: chg: comment position fix * dev: fix: govet lint errors * dev: fix: error related lint issues * dev: fix: bodyclose lint issues * dev: fix: some wsl lint issues * dev: fix: more wsl lint issues * dev: fix: errorcheck lint issues * dev: fix: solve more lint issues * dev: fix: more wsl lint issues * dev: fix: more errcheck lint issues * dev: fix: most of wsl lint issues * dev: fix: all remaining lint issues * dev: fix: t.Parallel called multiple times * dev: fix: tests failing due to t.Parallel * fix : runtime testcases * fix : testcase : config, addTxWithChain, burnAmount * fix : ethhash bor burn contract * fix : genspec config * fix : freezer, TestStateProcessorErrors * core,eth,miner: fix initial test cases (#922) * fix : TestTransactionIndices, testBeaconSync * fix : TestBeaconSync66 * core,eth: fix TestDeduplication, TestSyncAccountPerformance, TestTraceTransaction * fix : TestTxIndexer * rm : multiple coinbase balance * fix : testCommitInterruptExperimentBor * adding balance send to burntcontract back * Fix header encoding test * core,eth/tracers: fix TestPrestateWithDiffModeTracer * consensus/bor,eth/filters,miner,params,tests: fix mocks * fix : TestGraphQLConcurrentResolvers * fix : TestBuildPayload * common,core,miner: fix goleaks,duplicate init and inconsistent mutex (un)locks * fix : lint * fix : lint * fix : test-integration * fix : test-integration * core: restore AddFeeTransferLog post miner tipping * fix : TestGraphQLConcurrentResolvers * fix : deadlocks * rm: t.parallel from testQueueTimeLimiting tests * Merge branch 'develop' into mardizzone/upstream-merge * fix : lint * fix : test-integration * fix : TxDependency * add rpc.enabledeprecatedpersonal flag --------- Signed-off-by: Sungwoo Kim <git@sung-woo.kim> Signed-off-by: jsvisa <delweng@gmail.com> Co-authored-by: Péter Szilágyi <peterke@gmail.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: Chris Ziogas <ziogaschr@gmail.com> Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> Co-authored-by: rjl493456442 <garyrong0905@gmail.com> Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> Co-authored-by: Darioush Jalali <darioush.jalali@avalabs.org> Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: Patrick O'Grady <prohb125@gmail.com> Co-authored-by: ucwong <ucwong@126.com> Co-authored-by: Roman Krasiuk <rokrassyuk@gmail.com> Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com> Co-authored-by: Jason Yuan <jason.yuan869@gmail.com> Co-authored-by: Sungwoo Kim <git@sung-woo.kim> Co-authored-by: Yier <90763233+yierx@users.noreply.github.com> Co-authored-by: Catror <me@catror.com> Co-authored-by: Nate Armstrong <naterarmstrong@gmail.com> Co-authored-by: Dan Cline <6798349+Rjected@users.noreply.github.com> Co-authored-by: Peter (bitfly) <1674920+peterbitfly@users.noreply.github.com> Co-authored-by: PulsarAI <dev@pulsar-systems.fi> Co-authored-by: turboboost55 <7891737+turboboost55@users.noreply.github.com> Co-authored-by: Adrian Sutton <adrian@symphonious.net> Co-authored-by: Guruprasad Kamath <48196632+gurukamath@users.noreply.github.com> Co-authored-by: James Prestwich <10149425+prestwich@users.noreply.github.com> Co-authored-by: Daniel Fernandes <711733+daferna@users.noreply.github.com> Co-authored-by: Rafael Matias <rafael@skyle.net> Co-authored-by: xiyang <90125263+JBossBC@users.noreply.github.com> Co-authored-by: Roberto Bayardo <bayardo@alum.mit.edu> Co-authored-by: panicalways <113693386+panicalways@users.noreply.github.com> Co-authored-by: dwn1998 <42262393+dwn1998@users.noreply.github.com> Co-authored-by: s7v7nislands <s7v7nislands@gmail.com> Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com> Co-authored-by: Stephen Flynn <ssflynn@gmail.com> Co-authored-by: Stephen Flynn <stephen.flynn@gapac.com> Co-authored-by: Jonathan Otto <jonathan.otto@gmail.com> Co-authored-by: Delweng <delweng@gmail.com> Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com> Co-authored-by: aaronbuchwald <aaron.buchwald56@gmail.com> Co-authored-by: ucwong <ethereum2k@gmail.com> Co-authored-by: norwnd <112318969+norwnd@users.noreply.github.com> Co-authored-by: jwasinger <j-wasinger@hotmail.com> Co-authored-by: Adrian Sutton <adrian@oplabs.co> Co-authored-by: David Murdoch <187813+davidmurdoch@users.noreply.github.com> Co-authored-by: openex <openexkevin@gmail.com> Co-authored-by: “openex27” <“openexkevin@gmail.com”> Co-authored-by: sudeep <sudeepdino008@gmail.com> Co-authored-by: joohhnnn <68833933+joohhnnn@users.noreply.github.com> Co-authored-by: 0xTylerHolmes <tyler@ethereum.org> Co-authored-by: Exca-DK <85954505+Exca-DK@users.noreply.github.com> Co-authored-by: Exca-DK <dev@DESKTOP-RI45P4J.localdomain> Co-authored-by: Marius Kjærstad <mkjaerstad@protonmail.com> Co-authored-by: Parithosh Jayanthi <parithosh@indenwolken.xyz> Co-authored-by: noel <72006780+0x00Duke@users.noreply.github.com> Co-authored-by: Taeguk Kwon <xornrbboy@gmail.com> Co-authored-by: Anusha <63559942+anusha-ctrl@users.noreply.github.com> Co-authored-by: Alex Beregszaszi <alex@rtfs.hu> Co-authored-by: Shivam Sharma <shivam691999@gmail.com> Co-authored-by: Raneet Debnath <35629432+Raneet10@users.noreply.github.com> Co-authored-by: Raneet Debnath <raneetdebnath10@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com>
1349 lines
40 KiB
Go
1349 lines
40 KiB
Go
// Copyright 2018 The go-ethereum Authors
|
|
// This file is part of go-ethereum.
|
|
//
|
|
// go-ethereum is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// go-ethereum 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 General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math/big"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/ethereum/go-ethereum/accounts"
|
|
"github.com/ethereum/go-ethereum/accounts/keystore"
|
|
"github.com/ethereum/go-ethereum/cmd/utils"
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/common/hexutil"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
"github.com/ethereum/go-ethereum/internal/ethapi"
|
|
"github.com/ethereum/go-ethereum/internal/flags"
|
|
"github.com/ethereum/go-ethereum/log"
|
|
"github.com/ethereum/go-ethereum/node"
|
|
"github.com/ethereum/go-ethereum/params"
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
"github.com/ethereum/go-ethereum/rpc"
|
|
"github.com/ethereum/go-ethereum/signer/core"
|
|
"github.com/ethereum/go-ethereum/signer/core/apitypes"
|
|
"github.com/ethereum/go-ethereum/signer/fourbyte"
|
|
"github.com/ethereum/go-ethereum/signer/rules"
|
|
"github.com/ethereum/go-ethereum/signer/storage"
|
|
"github.com/mattn/go-colorable"
|
|
"github.com/mattn/go-isatty"
|
|
"github.com/urfave/cli/v2"
|
|
)
|
|
|
|
const legalWarning = `
|
|
WARNING!
|
|
|
|
Clef is an account management tool. It may, like any software, contain bugs.
|
|
|
|
Please take care to
|
|
- backup your keystore files,
|
|
- verify that the keystore(s) can be opened with your password.
|
|
|
|
Clef 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 General Public License for more details.
|
|
`
|
|
|
|
var (
|
|
logLevelFlag = &cli.IntFlag{
|
|
Name: "loglevel",
|
|
Value: 3,
|
|
Usage: "log level to emit to the screen",
|
|
}
|
|
advancedMode = &cli.BoolFlag{
|
|
Name: "advanced",
|
|
Usage: "If enabled, issues warnings instead of rejections for suspicious requests. Default off",
|
|
}
|
|
acceptFlag = &cli.BoolFlag{
|
|
Name: "suppress-bootwarn",
|
|
Usage: "If set, does not show the warning during boot",
|
|
}
|
|
keystoreFlag = &cli.StringFlag{
|
|
Name: "keystore",
|
|
Value: filepath.Join(node.DefaultDataDir(), "keystore"),
|
|
Usage: "Directory for the keystore",
|
|
}
|
|
configdirFlag = &cli.StringFlag{
|
|
Name: "configdir",
|
|
Value: DefaultConfigDir(),
|
|
Usage: "Directory for Clef configuration",
|
|
}
|
|
chainIdFlag = &cli.Int64Flag{
|
|
Name: "chainid",
|
|
Value: params.MainnetChainConfig.ChainID.Int64(),
|
|
Usage: "Chain id to use for signing (1=mainnet, 4=Rinkeby, 5=Goerli)",
|
|
}
|
|
rpcPortFlag = &cli.IntFlag{
|
|
Name: "http.port",
|
|
Usage: "HTTP-RPC server listening port",
|
|
Value: node.DefaultHTTPPort + 5,
|
|
Category: flags.APICategory,
|
|
}
|
|
signerSecretFlag = &cli.StringFlag{
|
|
Name: "signersecret",
|
|
Usage: "A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash",
|
|
}
|
|
customDBFlag = &cli.StringFlag{
|
|
Name: "4bytedb-custom",
|
|
Usage: "File used for writing new 4byte-identifiers submitted via API",
|
|
Value: "./4byte-custom.json",
|
|
}
|
|
auditLogFlag = &cli.StringFlag{
|
|
Name: "auditlog",
|
|
Usage: "File used to emit audit logs. Set to \"\" to disable",
|
|
Value: "audit.log",
|
|
}
|
|
ruleFlag = &cli.StringFlag{
|
|
Name: "rules",
|
|
Usage: "Path to the rule file to auto-authorize requests with",
|
|
}
|
|
stdiouiFlag = &cli.BoolFlag{
|
|
Name: "stdio-ui",
|
|
Usage: "Use STDIN/STDOUT as a channel for an external UI. " +
|
|
"This means that an STDIN/STDOUT is used for RPC-communication with a e.g. a graphical user " +
|
|
"interface, and can be used when Clef is started by an external process.",
|
|
}
|
|
testFlag = &cli.BoolFlag{
|
|
Name: "stdio-ui-test",
|
|
Usage: "Mechanism to test interface between Clef and UI. Requires 'stdio-ui'.",
|
|
}
|
|
initCommand = &cli.Command{
|
|
Action: initializeSecrets,
|
|
Name: "init",
|
|
Usage: "Initialize the signer, generate secret storage",
|
|
ArgsUsage: "",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
configdirFlag,
|
|
},
|
|
Description: `
|
|
The init command generates a master seed which Clef can use to store credentials and data needed for
|
|
the rule-engine to work.`,
|
|
}
|
|
attestCommand = &cli.Command{
|
|
Action: attestFile,
|
|
Name: "attest",
|
|
Usage: "Attest that a js-file is to be used",
|
|
ArgsUsage: "<sha256sum>",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
configdirFlag,
|
|
signerSecretFlag,
|
|
},
|
|
Description: `
|
|
The attest command stores the sha256 of the rule.js-file that you want to use for automatic processing of
|
|
incoming requests.
|
|
|
|
Whenever you make an edit to the rule file, you need to use attestation to tell
|
|
Clef that the file is 'safe' to execute.`,
|
|
}
|
|
setCredentialCommand = &cli.Command{
|
|
Action: setCredential,
|
|
Name: "setpw",
|
|
Usage: "Store a credential for a keystore file",
|
|
ArgsUsage: "<address>",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
configdirFlag,
|
|
signerSecretFlag,
|
|
},
|
|
Description: `
|
|
The setpw command stores a password for a given address (keyfile).
|
|
`}
|
|
delCredentialCommand = &cli.Command{
|
|
Action: removeCredential,
|
|
Name: "delpw",
|
|
Usage: "Remove a credential for a keystore file",
|
|
ArgsUsage: "<address>",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
configdirFlag,
|
|
signerSecretFlag,
|
|
},
|
|
Description: `
|
|
The delpw command removes a password for a given address (keyfile).
|
|
`}
|
|
newAccountCommand = &cli.Command{
|
|
Action: newAccount,
|
|
Name: "newaccount",
|
|
Usage: "Create a new account",
|
|
ArgsUsage: "",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
keystoreFlag,
|
|
utils.LightKDFFlag,
|
|
acceptFlag,
|
|
},
|
|
Description: `
|
|
The newaccount command creates a new keystore-backed account. It is a convenience-method
|
|
which can be used in lieu of an external UI.
|
|
`}
|
|
gendocCommand = &cli.Command{
|
|
Action: GenDoc,
|
|
Name: "gendoc",
|
|
Usage: "Generate documentation about json-rpc format",
|
|
Description: `
|
|
The gendoc generates example structures of the json-rpc communication types.
|
|
`}
|
|
listAccountsCommand = &cli.Command{
|
|
Action: listAccounts,
|
|
Name: "list-accounts",
|
|
Usage: "List accounts in the keystore",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
keystoreFlag,
|
|
utils.LightKDFFlag,
|
|
acceptFlag,
|
|
},
|
|
Description: `
|
|
Lists the accounts in the keystore.
|
|
`}
|
|
listWalletsCommand = &cli.Command{
|
|
Action: listWallets,
|
|
Name: "list-wallets",
|
|
Usage: "List wallets known to Clef",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
keystoreFlag,
|
|
utils.LightKDFFlag,
|
|
acceptFlag,
|
|
},
|
|
Description: `
|
|
Lists the wallets known to Clef.
|
|
`}
|
|
importRawCommand = &cli.Command{
|
|
Action: accountImport,
|
|
Name: "importraw",
|
|
Usage: "Import a hex-encoded private key.",
|
|
ArgsUsage: "<keyfile>",
|
|
Flags: []cli.Flag{
|
|
logLevelFlag,
|
|
keystoreFlag,
|
|
utils.LightKDFFlag,
|
|
acceptFlag,
|
|
},
|
|
Description: `
|
|
Imports an unencrypted private key from <keyfile> and creates a new account.
|
|
Prints the address.
|
|
The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
|
|
The account is saved in encrypted format, you are prompted for a password.
|
|
`}
|
|
)
|
|
|
|
var app = flags.NewApp("Manage Ethereum account operations")
|
|
|
|
func init() {
|
|
app.Name = "Clef"
|
|
app.Flags = []cli.Flag{
|
|
logLevelFlag,
|
|
keystoreFlag,
|
|
configdirFlag,
|
|
chainIdFlag,
|
|
utils.LightKDFFlag,
|
|
utils.NoUSBFlag,
|
|
utils.SmartCardDaemonPathFlag,
|
|
utils.HTTPListenAddrFlag,
|
|
utils.HTTPVirtualHostsFlag,
|
|
utils.IPCDisabledFlag,
|
|
utils.IPCPathFlag,
|
|
utils.HTTPEnabledFlag,
|
|
rpcPortFlag,
|
|
signerSecretFlag,
|
|
customDBFlag,
|
|
auditLogFlag,
|
|
ruleFlag,
|
|
stdiouiFlag,
|
|
testFlag,
|
|
advancedMode,
|
|
acceptFlag,
|
|
}
|
|
app.Action = signer
|
|
app.Commands = []*cli.Command{initCommand,
|
|
attestCommand,
|
|
setCredentialCommand,
|
|
delCredentialCommand,
|
|
newAccountCommand,
|
|
importRawCommand,
|
|
gendocCommand,
|
|
listAccountsCommand,
|
|
listWalletsCommand,
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
if err := app.Run(os.Args); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func initializeSecrets(c *cli.Context) error {
|
|
// Get past the legal message
|
|
if err := initialize(c); err != nil {
|
|
return err
|
|
}
|
|
// Ensure the master key does not yet exist, we're not willing to overwrite
|
|
configDir := c.String(configdirFlag.Name)
|
|
if err := os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
|
|
return err
|
|
}
|
|
|
|
location := filepath.Join(configDir, "masterseed.json")
|
|
if _, err := os.Stat(location); err == nil {
|
|
return fmt.Errorf("master key %v already exists, will not overwrite", location)
|
|
}
|
|
// Key file does not exist yet, generate a new one and encrypt it
|
|
masterSeed := make([]byte, 256)
|
|
|
|
num, err := io.ReadFull(rand.Reader, masterSeed)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if num != len(masterSeed) {
|
|
return fmt.Errorf("failed to read enough random")
|
|
}
|
|
|
|
n, p := keystore.StandardScryptN, keystore.StandardScryptP
|
|
|
|
if c.Bool(utils.LightKDFFlag.Name) {
|
|
n, p = keystore.LightScryptN, keystore.LightScryptP
|
|
}
|
|
|
|
text := "The master seed of clef will be locked with a password.\nPlease specify a password. Do not forget this password!"
|
|
|
|
var password string
|
|
|
|
for {
|
|
password = utils.GetPassPhrase(text, true)
|
|
if err := core.ValidatePasswordFormat(password); err != nil {
|
|
fmt.Printf("invalid password: %v\n", err)
|
|
} else {
|
|
fmt.Println()
|
|
break
|
|
}
|
|
}
|
|
|
|
cipherSeed, err := encryptSeed(masterSeed, []byte(password), n, p)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to encrypt master seed: %v", err)
|
|
}
|
|
// Double check the master key path to ensure nothing wrote there in between
|
|
if err = os.Mkdir(configDir, 0700); err != nil && !os.IsExist(err) {
|
|
return err
|
|
}
|
|
|
|
if _, err := os.Stat(location); err == nil {
|
|
return fmt.Errorf("master key %v already exists, will not overwrite", location)
|
|
}
|
|
// Write the file and print the usual warning message
|
|
if err = os.WriteFile(location, cipherSeed, 0400); err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("A master seed has been generated into %s\n", location)
|
|
fmt.Printf(`
|
|
This is required to be able to store credentials, such as:
|
|
* Passwords for keystores (used by rule engine)
|
|
* Storage for JavaScript auto-signing rules
|
|
* Hash of JavaScript rule-file
|
|
|
|
You should treat 'masterseed.json' with utmost secrecy and make a backup of it!
|
|
* The password is necessary but not enough, you need to back up the master seed too!
|
|
* The master seed does not contain your accounts, those need to be backed up separately!
|
|
|
|
`)
|
|
|
|
return nil
|
|
}
|
|
|
|
func attestFile(ctx *cli.Context) error {
|
|
if ctx.NArg() < 1 {
|
|
utils.Fatalf("This command requires an argument.")
|
|
}
|
|
|
|
if err := initialize(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
stretchedKey, err := readMasterKey(ctx, nil)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
configDir := ctx.String(configdirFlag.Name)
|
|
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
|
|
confKey := crypto.Keccak256([]byte("config"), stretchedKey)
|
|
|
|
// Initialize the encrypted storages
|
|
configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confKey)
|
|
val := ctx.Args().First()
|
|
configStorage.Put("ruleset_sha256", val)
|
|
log.Info("Ruleset attestation updated", "sha256", val)
|
|
|
|
return nil
|
|
}
|
|
|
|
func initInternalApi(c *cli.Context) (*core.UIServerAPI, core.UIClientAPI, error) {
|
|
if err := initialize(c); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
var (
|
|
ui = core.NewCommandlineUI()
|
|
pwStorage storage.Storage = &storage.NoStorage{}
|
|
ksLoc = c.String(keystoreFlag.Name)
|
|
lightKdf = c.Bool(utils.LightKDFFlag.Name)
|
|
)
|
|
|
|
am := core.StartClefAccountManager(ksLoc, true, lightKdf, "")
|
|
api := core.NewSignerAPI(am, 0, true, ui, nil, false, pwStorage)
|
|
internalApi := core.NewUIServerAPI(api)
|
|
|
|
return internalApi, ui, nil
|
|
}
|
|
|
|
func setCredential(ctx *cli.Context) error {
|
|
if ctx.NArg() < 1 {
|
|
utils.Fatalf("This command requires an address to be passed as an argument")
|
|
}
|
|
|
|
if err := initialize(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
addr := ctx.Args().First()
|
|
if !common.IsHexAddress(addr) {
|
|
utils.Fatalf("Invalid address specified: %s", addr)
|
|
}
|
|
|
|
address := common.HexToAddress(addr)
|
|
password := utils.GetPassPhrase("Please enter a password to store for this address:", true)
|
|
|
|
fmt.Println()
|
|
|
|
stretchedKey, err := readMasterKey(ctx, nil)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
configDir := ctx.String(configdirFlag.Name)
|
|
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
|
|
pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
|
|
|
|
pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
|
|
pwStorage.Put(address.Hex(), password)
|
|
|
|
log.Info("Credential store updated", "set", address)
|
|
|
|
return nil
|
|
}
|
|
|
|
func removeCredential(ctx *cli.Context) error {
|
|
if ctx.NArg() < 1 {
|
|
utils.Fatalf("This command requires an address to be passed as an argument")
|
|
}
|
|
|
|
if err := initialize(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
addr := ctx.Args().First()
|
|
if !common.IsHexAddress(addr) {
|
|
utils.Fatalf("Invalid address specified: %s", addr)
|
|
}
|
|
|
|
address := common.HexToAddress(addr)
|
|
|
|
stretchedKey, err := readMasterKey(ctx, nil)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
configDir := ctx.String(configdirFlag.Name)
|
|
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
|
|
pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
|
|
|
|
pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
|
|
pwStorage.Del(address.Hex())
|
|
|
|
log.Info("Credential store updated", "unset", address)
|
|
|
|
return nil
|
|
}
|
|
|
|
func initialize(c *cli.Context) error {
|
|
// Set up the logger to print everything
|
|
logOutput := os.Stdout
|
|
if c.Bool(stdiouiFlag.Name) {
|
|
logOutput = os.Stderr
|
|
// If using the stdioui, we can't do the 'confirm'-flow
|
|
if !c.Bool(acceptFlag.Name) {
|
|
fmt.Fprint(logOutput, legalWarning)
|
|
}
|
|
} else if !c.Bool(acceptFlag.Name) {
|
|
if !confirm(legalWarning) {
|
|
return fmt.Errorf("aborted by user")
|
|
}
|
|
|
|
fmt.Println()
|
|
}
|
|
|
|
usecolor := (isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())) && os.Getenv("TERM") != "dumb"
|
|
output := io.Writer(logOutput)
|
|
|
|
if usecolor {
|
|
output = colorable.NewColorable(logOutput)
|
|
}
|
|
|
|
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(c.Int(logLevelFlag.Name)), log.StreamHandler(output, log.TerminalFormat(usecolor))))
|
|
|
|
return nil
|
|
}
|
|
|
|
func newAccount(c *cli.Context) error {
|
|
internalApi, _, err := initInternalApi(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
addr, err := internalApi.New(context.Background())
|
|
|
|
if err == nil {
|
|
fmt.Printf("Generated account %v\n", addr.String())
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func listAccounts(c *cli.Context) error {
|
|
internalApi, _, err := initInternalApi(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
accs, err := internalApi.ListAccounts(context.Background())
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(accs) == 0 {
|
|
fmt.Println("\nThe keystore is empty.")
|
|
}
|
|
|
|
fmt.Println()
|
|
|
|
for _, account := range accs {
|
|
fmt.Printf("%v (%v)\n", account.Address, account.URL)
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func listWallets(c *cli.Context) error {
|
|
internalApi, _, err := initInternalApi(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
wallets := internalApi.ListWallets()
|
|
|
|
if len(wallets) == 0 {
|
|
fmt.Println("\nThere are no wallets.")
|
|
}
|
|
|
|
fmt.Println()
|
|
|
|
for i, wallet := range wallets {
|
|
fmt.Printf("- Wallet %d at %v (%v %v)\n", i, wallet.URL, wallet.Status, wallet.Failure)
|
|
|
|
for j, acc := range wallet.Accounts {
|
|
fmt.Printf(" -Account %d: %v (%v)\n", j, acc.Address, acc.URL)
|
|
}
|
|
|
|
fmt.Println()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// accountImport imports a raw hexadecimal private key via CLI.
|
|
func accountImport(c *cli.Context) error {
|
|
if c.Args().Len() != 1 {
|
|
return errors.New("<keyfile> must be given as first argument.")
|
|
}
|
|
|
|
internalApi, ui, err := initInternalApi(c)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
pKey, err := crypto.LoadECDSA(c.Args().First())
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
readPw := func(prompt string) (string, error) {
|
|
resp, err := ui.OnInputRequired(core.UserInputRequest{
|
|
Title: "Password",
|
|
Prompt: prompt,
|
|
IsPassword: true,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return resp.Text, nil
|
|
}
|
|
first, err := readPw("Please enter a password for the imported account")
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
second, err := readPw("Please repeat the password you just entered")
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if first != second {
|
|
return errors.New("Passwords do not match")
|
|
}
|
|
|
|
acc, err := internalApi.ImportRawKey(hex.EncodeToString(crypto.FromECDSA(pKey)), first)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
ui.ShowInfo(fmt.Sprintf(`Key imported:
|
|
Address %v
|
|
Keystore file: %v
|
|
|
|
The key is now encrypted; losing the password will result in permanently losing
|
|
access to the key and all associated funds!
|
|
|
|
Make sure to backup keystore and passwords in a safe location.`,
|
|
acc.Address, acc.URL.Path))
|
|
|
|
return nil
|
|
}
|
|
|
|
// ipcEndpoint resolves an IPC endpoint based on a configured value, taking into
|
|
// account the set data folders as well as the designated platform we're currently
|
|
// running on.
|
|
func ipcEndpoint(ipcPath, datadir string) string {
|
|
// On windows we can only use plain top-level pipes
|
|
if runtime.GOOS == "windows" {
|
|
if strings.HasPrefix(ipcPath, `\\.\pipe\`) {
|
|
return ipcPath
|
|
}
|
|
|
|
return `\\.\pipe\` + ipcPath
|
|
}
|
|
// Resolve names into the data directory full paths otherwise
|
|
if filepath.Base(ipcPath) == ipcPath {
|
|
if datadir == "" {
|
|
return filepath.Join(os.TempDir(), ipcPath)
|
|
}
|
|
|
|
return filepath.Join(datadir, ipcPath)
|
|
}
|
|
|
|
return ipcPath
|
|
}
|
|
|
|
func signer(c *cli.Context) error {
|
|
// If we have some unrecognized command, bail out
|
|
if c.NArg() > 0 {
|
|
return fmt.Errorf("invalid command: %q", c.Args().First())
|
|
}
|
|
|
|
if err := initialize(c); err != nil {
|
|
return err
|
|
}
|
|
|
|
var (
|
|
ui core.UIClientAPI
|
|
)
|
|
|
|
if c.Bool(stdiouiFlag.Name) {
|
|
log.Info("Using stdin/stdout as UI-channel")
|
|
|
|
ui = core.NewStdIOUI()
|
|
} else {
|
|
log.Info("Using CLI as UI-channel")
|
|
|
|
ui = core.NewCommandlineUI()
|
|
}
|
|
// 4bytedb data
|
|
fourByteLocal := c.String(customDBFlag.Name)
|
|
|
|
db, err := fourbyte.NewWithFile(fourByteLocal)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
embeds, locals := db.Size()
|
|
log.Info("Loaded 4byte database", "embeds", embeds, "locals", locals, "local", fourByteLocal)
|
|
|
|
var (
|
|
api core.ExternalAPI
|
|
pwStorage storage.Storage = &storage.NoStorage{}
|
|
)
|
|
|
|
configDir := c.String(configdirFlag.Name)
|
|
|
|
if stretchedKey, err := readMasterKey(c, ui); err != nil {
|
|
log.Warn("Failed to open master, rules disabled", "err", err)
|
|
} else {
|
|
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), stretchedKey)[:10]))
|
|
|
|
// Generate domain specific keys
|
|
pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
|
|
jskey := crypto.Keccak256([]byte("jsstorage"), stretchedKey)
|
|
confkey := crypto.Keccak256([]byte("config"), stretchedKey)
|
|
|
|
// Initialize the encrypted storages
|
|
pwStorage = storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
|
|
jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey)
|
|
configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey)
|
|
|
|
// Do we have a rule-file?
|
|
if ruleFile := c.String(ruleFlag.Name); ruleFile != "" {
|
|
ruleJS, err := os.ReadFile(ruleFile)
|
|
if err != nil {
|
|
log.Warn("Could not load rules, disabling", "file", ruleFile, "err", err)
|
|
} else {
|
|
shasum := sha256.Sum256(ruleJS)
|
|
foundShaSum := hex.EncodeToString(shasum[:])
|
|
storedShasum, _ := configStorage.Get("ruleset_sha256")
|
|
|
|
if storedShasum != foundShaSum {
|
|
log.Warn("Rule hash not attested, disabling", "hash", foundShaSum, "attested", storedShasum)
|
|
} else {
|
|
// Initialize rules
|
|
ruleEngine, err := rules.NewRuleEvaluator(ui, jsStorage)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
ruleEngine.Init(string(ruleJS))
|
|
ui = ruleEngine
|
|
|
|
log.Info("Rule engine configured", "file", c.String(ruleFlag.Name))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var (
|
|
chainId = c.Int64(chainIdFlag.Name)
|
|
ksLoc = c.String(keystoreFlag.Name)
|
|
lightKdf = c.Bool(utils.LightKDFFlag.Name)
|
|
advanced = c.Bool(advancedMode.Name)
|
|
nousb = c.Bool(utils.NoUSBFlag.Name)
|
|
scpath = c.String(utils.SmartCardDaemonPathFlag.Name)
|
|
)
|
|
|
|
log.Info("Starting signer", "chainid", chainId, "keystore", ksLoc,
|
|
"light-kdf", lightKdf, "advanced", advanced)
|
|
|
|
am := core.StartClefAccountManager(ksLoc, nousb, lightKdf, scpath)
|
|
apiImpl := core.NewSignerAPI(am, chainId, nousb, ui, db, advanced, pwStorage)
|
|
|
|
// Establish the bidirectional communication, by creating a new UI backend and registering
|
|
// it with the UI.
|
|
ui.RegisterUIServer(core.NewUIServerAPI(apiImpl))
|
|
api = apiImpl
|
|
|
|
// Audit logging
|
|
if logfile := c.String(auditLogFlag.Name); logfile != "" {
|
|
api, err = core.NewAuditLogger(logfile, api)
|
|
if err != nil {
|
|
utils.Fatalf(err.Error())
|
|
}
|
|
|
|
log.Info("Audit logs configured", "file", logfile)
|
|
}
|
|
// register signer API with server
|
|
var (
|
|
extapiURL = "n/a"
|
|
ipcapiURL = "n/a"
|
|
)
|
|
|
|
rpcAPI := []rpc.API{
|
|
{
|
|
Namespace: "account",
|
|
Service: api,
|
|
},
|
|
}
|
|
|
|
if c.Bool(utils.HTTPEnabledFlag.Name) {
|
|
vhosts := utils.SplitAndTrim(c.String(utils.HTTPVirtualHostsFlag.Name))
|
|
cors := utils.SplitAndTrim(c.String(utils.HTTPCORSDomainFlag.Name))
|
|
|
|
srv := rpc.NewServer("", 0, 0)
|
|
err := node.RegisterApis(rpcAPI, []string{"account"}, srv)
|
|
if err != nil {
|
|
utils.Fatalf("Could not register API: %w", err)
|
|
}
|
|
|
|
handler := node.NewHTTPHandlerStack(srv, cors, vhosts, nil)
|
|
|
|
// set port
|
|
port := c.Int(rpcPortFlag.Name)
|
|
|
|
// start http server
|
|
httpEndpoint := fmt.Sprintf("%s:%d", c.String(utils.HTTPListenAddrFlag.Name), port)
|
|
|
|
httpServer, addr, err := node.StartHTTPEndpoint(httpEndpoint, rpc.DefaultHTTPTimeouts, handler)
|
|
if err != nil {
|
|
utils.Fatalf("Could not start RPC api: %v", err)
|
|
}
|
|
|
|
extapiURL = fmt.Sprintf("http://%v/", addr)
|
|
log.Info("HTTP endpoint opened", "url", extapiURL)
|
|
|
|
defer func() {
|
|
// Don't bother imposing a timeout here.
|
|
httpServer.Shutdown(context.Background())
|
|
log.Info("HTTP endpoint closed", "url", extapiURL)
|
|
}()
|
|
}
|
|
|
|
if !c.Bool(utils.IPCDisabledFlag.Name) {
|
|
givenPath := c.String(utils.IPCPathFlag.Name)
|
|
ipcapiURL = ipcEndpoint(filepath.Join(givenPath, "clef.ipc"), configDir)
|
|
|
|
listener, _, err := rpc.StartIPCEndpoint(ipcapiURL, rpcAPI)
|
|
if err != nil {
|
|
utils.Fatalf("Could not start IPC api: %v", err)
|
|
}
|
|
|
|
log.Info("IPC endpoint opened", "url", ipcapiURL)
|
|
|
|
defer func() {
|
|
listener.Close()
|
|
log.Info("IPC endpoint closed", "url", ipcapiURL)
|
|
}()
|
|
}
|
|
|
|
if c.Bool(testFlag.Name) {
|
|
log.Info("Performing UI test")
|
|
|
|
go testExternalUI(apiImpl)
|
|
}
|
|
|
|
ui.OnSignerStartup(core.StartupInfo{
|
|
Info: map[string]interface{}{
|
|
"intapi_version": core.InternalAPIVersion,
|
|
"extapi_version": core.ExternalAPIVersion,
|
|
"extapi_http": extapiURL,
|
|
"extapi_ipc": ipcapiURL,
|
|
}})
|
|
|
|
abortChan := make(chan os.Signal, 1)
|
|
signal.Notify(abortChan, os.Interrupt)
|
|
|
|
sig := <-abortChan
|
|
log.Info("Exiting...", "signal", sig)
|
|
|
|
return nil
|
|
}
|
|
|
|
// DefaultConfigDir is the default config directory to use for the vaults and other
|
|
// persistence requirements.
|
|
func DefaultConfigDir() string {
|
|
// Try to place the data folder in the user's home dir
|
|
home := flags.HomeDir()
|
|
if home != "" {
|
|
if runtime.GOOS == "darwin" {
|
|
return filepath.Join(home, "Library", "Signer")
|
|
} else if runtime.GOOS == "windows" {
|
|
appdata := os.Getenv("APPDATA")
|
|
if appdata != "" {
|
|
return filepath.Join(appdata, "Signer")
|
|
}
|
|
|
|
return filepath.Join(home, "AppData", "Roaming", "Signer")
|
|
}
|
|
|
|
return filepath.Join(home, ".clef")
|
|
}
|
|
// As we cannot guess a stable location, return empty and handle later
|
|
return ""
|
|
}
|
|
|
|
func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) {
|
|
var (
|
|
file string
|
|
configDir = ctx.String(configdirFlag.Name)
|
|
)
|
|
|
|
if ctx.IsSet(signerSecretFlag.Name) {
|
|
file = ctx.String(signerSecretFlag.Name)
|
|
} else {
|
|
file = filepath.Join(configDir, "masterseed.json")
|
|
}
|
|
|
|
if err := checkFile(file); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cipherKey, err := os.ReadFile(file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var password string
|
|
// If ui is not nil, get the password from ui.
|
|
if ui != nil {
|
|
resp, err := ui.OnInputRequired(core.UserInputRequest{
|
|
Title: "Master Password",
|
|
Prompt: "Please enter the password to decrypt the master seed",
|
|
IsPassword: true})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
password = resp.Text
|
|
} else {
|
|
password = utils.GetPassPhrase("Decrypt master seed of clef", false)
|
|
}
|
|
|
|
masterSeed, err := decryptSeed(cipherKey, password)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decrypt the master seed of clef")
|
|
}
|
|
|
|
if len(masterSeed) < 256 {
|
|
return nil, fmt.Errorf("master seed of insufficient length, expected >255 bytes, got %d", len(masterSeed))
|
|
}
|
|
// Create vault location
|
|
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterSeed)[:10]))
|
|
|
|
err = os.Mkdir(vaultLocation, 0700)
|
|
if err != nil && !os.IsExist(err) {
|
|
return nil, err
|
|
}
|
|
|
|
return masterSeed, nil
|
|
}
|
|
|
|
// checkFile is a convenience function to check if a file
|
|
// * exists
|
|
// * is mode 0400 (unix only)
|
|
func checkFile(filename string) error {
|
|
info, err := os.Stat(filename)
|
|
if err != nil {
|
|
return fmt.Errorf("failed stat on %s: %v", filename, err)
|
|
}
|
|
// Check the unix permission bits
|
|
// However, on windows, we cannot use the unix perm-bits, see
|
|
// https://github.com/ethereum/go-ethereum/issues/20123
|
|
if runtime.GOOS != "windows" && info.Mode().Perm()&0377 != 0 {
|
|
return fmt.Errorf("file (%v) has insecure file permissions (%v)", filename, info.Mode().String())
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// confirm displays a text and asks for user confirmation
|
|
func confirm(text string) bool {
|
|
fmt.Print(text)
|
|
fmt.Printf("\nEnter 'ok' to proceed:\n> ")
|
|
|
|
text, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
|
if err != nil {
|
|
log.Crit("Failed to read user input", "err", err)
|
|
}
|
|
|
|
if text := strings.TrimSpace(text); text == "ok" {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func testExternalUI(api *core.SignerAPI) {
|
|
ctx := context.WithValue(context.Background(), "remote", "clef binary")
|
|
ctx = context.WithValue(ctx, "scheme", "in-proc")
|
|
ctx = context.WithValue(ctx, "local", "main")
|
|
errs := make([]string, 0)
|
|
|
|
a := common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
|
|
addErr := func(errStr string) {
|
|
log.Info("Test error", "err", errStr)
|
|
errs = append(errs, errStr)
|
|
}
|
|
|
|
queryUser := func(q string) string {
|
|
resp, err := api.UI.OnInputRequired(core.UserInputRequest{
|
|
Title: "Testing",
|
|
Prompt: q,
|
|
})
|
|
if err != nil {
|
|
addErr(err.Error())
|
|
}
|
|
|
|
return resp.Text
|
|
}
|
|
expectResponse := func(testcase, question, expect string) {
|
|
if got := queryUser(question); got != expect {
|
|
addErr(fmt.Sprintf("%s: got %v, expected %v", testcase, got, expect))
|
|
}
|
|
}
|
|
expectApprove := func(testcase string, err error) {
|
|
if err == nil || err == accounts.ErrUnknownAccount {
|
|
return
|
|
}
|
|
|
|
addErr(fmt.Sprintf("%v: expected no error, got %v", testcase, err.Error()))
|
|
}
|
|
expectDeny := func(testcase string, err error) {
|
|
if err == nil || err != core.ErrRequestDenied {
|
|
addErr(fmt.Sprintf("%v: expected ErrRequestDenied, got %v", testcase, err))
|
|
}
|
|
}
|
|
|
|
var delay = 1 * time.Second
|
|
// Test display of info and error
|
|
{
|
|
api.UI.ShowInfo("If you see this message, enter 'yes' to next question")
|
|
time.Sleep(delay)
|
|
expectResponse("showinfo", "Did you see the message? [yes/no]", "yes")
|
|
api.UI.ShowError("If you see this message, enter 'yes' to the next question")
|
|
time.Sleep(delay)
|
|
expectResponse("showerror", "Did you see the message? [yes/no]", "yes")
|
|
}
|
|
{ // Sign data test - clique header
|
|
api.UI.ShowInfo("Please approve the next request for signing a clique header")
|
|
time.Sleep(delay)
|
|
|
|
cliqueHeader := types.Header{
|
|
ParentHash: common.HexToHash("0000H45H"),
|
|
UncleHash: common.HexToHash("0000H45H"),
|
|
Coinbase: common.HexToAddress("0000H45H"),
|
|
Root: common.HexToHash("0000H00H"),
|
|
TxHash: common.HexToHash("0000H45H"),
|
|
ReceiptHash: common.HexToHash("0000H45H"),
|
|
Difficulty: big.NewInt(1337),
|
|
Number: big.NewInt(1337),
|
|
GasLimit: 1338,
|
|
GasUsed: 1338,
|
|
Time: 1338,
|
|
Extra: []byte("Extra data Extra data Extra data Extra data Extra data Extra data Extra data Extra data"),
|
|
MixDigest: common.HexToHash("0x0000H45H"),
|
|
}
|
|
|
|
cliqueRlp, err := rlp.EncodeToBytes(cliqueHeader)
|
|
if err != nil {
|
|
utils.Fatalf("Should not error: %v", err)
|
|
}
|
|
|
|
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
|
_, err = api.SignData(ctx, accounts.MimetypeClique, *addr, hexutil.Encode(cliqueRlp))
|
|
expectApprove("signdata - clique header", err)
|
|
}
|
|
{ // Sign data test - typed data
|
|
api.UI.ShowInfo("Please approve the next request for signing EIP-712 typed data")
|
|
time.Sleep(delay)
|
|
|
|
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
|
data := `{"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"test","type":"uint8"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":"1","verifyingContract":"0xCCCcccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","test":"3","wallet":"0xcD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB","test":"2"},"contents":"Hello, Bob!"}}`
|
|
//_, err := api.SignData(ctx, accounts.MimetypeTypedData, *addr, hexutil.Encode([]byte(data)))
|
|
var typedData apitypes.TypedData
|
|
|
|
json.Unmarshal([]byte(data), &typedData)
|
|
_, err := api.SignTypedData(ctx, *addr, typedData)
|
|
expectApprove("sign 712 typed data", err)
|
|
}
|
|
{ // Sign data test - plain text
|
|
api.UI.ShowInfo("Please approve the next request for signing text")
|
|
time.Sleep(delay)
|
|
|
|
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
|
_, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
|
|
expectApprove("signdata - text", err)
|
|
}
|
|
{ // Sign data test - plain text reject
|
|
api.UI.ShowInfo("Please deny the next request for signing text")
|
|
time.Sleep(delay)
|
|
|
|
addr, _ := common.NewMixedcaseAddressFromString("0x0011223344556677889900112233445566778899")
|
|
_, err := api.SignData(ctx, accounts.MimetypeTextPlain, *addr, hexutil.Encode([]byte("hello world")))
|
|
expectDeny("signdata - text", err)
|
|
}
|
|
{ // Sign transaction
|
|
api.UI.ShowInfo("Please reject next transaction")
|
|
time.Sleep(delay)
|
|
|
|
data := hexutil.Bytes([]byte{})
|
|
to := common.NewMixedcaseAddress(a)
|
|
tx := apitypes.SendTxArgs{
|
|
Data: &data,
|
|
Nonce: 0x1,
|
|
Value: hexutil.Big(*big.NewInt(6)),
|
|
From: common.NewMixedcaseAddress(a),
|
|
To: &to,
|
|
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
|
Gas: 1000,
|
|
Input: nil,
|
|
}
|
|
_, err := api.SignTransaction(ctx, tx, nil)
|
|
expectDeny("signtransaction [1]", err)
|
|
expectResponse("signtransaction [2]", "Did you see any warnings for the last transaction? (yes/no)", "no")
|
|
}
|
|
{ // Listing
|
|
api.UI.ShowInfo("Please reject listing-request")
|
|
time.Sleep(delay)
|
|
|
|
_, err := api.List(ctx)
|
|
expectDeny("list", err)
|
|
}
|
|
{ // Import
|
|
api.UI.ShowInfo("Please reject new account-request")
|
|
time.Sleep(delay)
|
|
|
|
_, err := api.New(ctx)
|
|
expectDeny("newaccount", err)
|
|
}
|
|
{ // Metadata
|
|
api.UI.ShowInfo("Please check if you see the Origin in next listing (approve or deny)")
|
|
time.Sleep(delay)
|
|
api.List(context.WithValue(ctx, "Origin", "origin.com"))
|
|
expectResponse("metadata - origin", "Did you see origin (origin.com)? [yes/no] ", "yes")
|
|
}
|
|
|
|
for _, e := range errs {
|
|
log.Error(e)
|
|
}
|
|
|
|
result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n"))
|
|
api.UI.ShowInfo(result)
|
|
}
|
|
|
|
type encryptedSeedStorage struct {
|
|
Description string `json:"description"`
|
|
Version int `json:"version"`
|
|
Params keystore.CryptoJSON `json:"params"`
|
|
}
|
|
|
|
// encryptSeed uses a similar scheme as the keystore uses, but with a different wrapping,
|
|
// to encrypt the master seed
|
|
func encryptSeed(seed []byte, auth []byte, scryptN, scryptP int) ([]byte, error) {
|
|
cryptoStruct, err := keystore.EncryptDataV3(seed, auth, scryptN, scryptP)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return json.Marshal(&encryptedSeedStorage{"Clef seed", 1, cryptoStruct})
|
|
}
|
|
|
|
// decryptSeed decrypts the master seed
|
|
func decryptSeed(keyjson []byte, auth string) ([]byte, error) {
|
|
var encSeed encryptedSeedStorage
|
|
if err := json.Unmarshal(keyjson, &encSeed); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if encSeed.Version != 1 {
|
|
log.Warn(fmt.Sprintf("unsupported encryption format of seed: %d, operation will likely fail", encSeed.Version))
|
|
}
|
|
|
|
seed, err := keystore.DecryptDataV3(encSeed.Params, auth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return seed, err
|
|
}
|
|
|
|
// GenDoc outputs examples of all structures used in json-rpc communication
|
|
func GenDoc(ctx *cli.Context) error {
|
|
var (
|
|
a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
|
|
b = common.HexToAddress("0x1111111122222222222233333333334444444444")
|
|
meta = core.Metadata{
|
|
Scheme: "http",
|
|
Local: "localhost:8545",
|
|
Origin: "www.malicious.ru",
|
|
Remote: "localhost:9999",
|
|
UserAgent: "Firefox 3.2",
|
|
}
|
|
output []string
|
|
add = func(name, desc string, v interface{}) {
|
|
if data, err := json.MarshalIndent(v, "", " "); err == nil {
|
|
output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data))
|
|
} else {
|
|
log.Error("Error generating output", "err", err)
|
|
}
|
|
}
|
|
)
|
|
|
|
{ // Sign plain text request
|
|
desc := "SignDataRequest contains information about a pending request to sign some data. " +
|
|
"The data to be signed can be of various types, defined by content-type. Clef has done most " +
|
|
"of the work in canonicalizing and making sense of the data, and it's up to the UI to present" +
|
|
"the user with the contents of the `message`"
|
|
sighash, msg := accounts.TextAndHash([]byte("hello world"))
|
|
messages := []*apitypes.NameValueType{{Name: "message", Value: msg, Typ: accounts.MimetypeTextPlain}}
|
|
|
|
add("SignDataRequest", desc, &core.SignDataRequest{
|
|
Address: common.NewMixedcaseAddress(a),
|
|
Meta: meta,
|
|
ContentType: accounts.MimetypeTextPlain,
|
|
Rawdata: []byte(msg),
|
|
Messages: messages,
|
|
Hash: sighash})
|
|
}
|
|
{ // Sign plain text response
|
|
add("SignDataResponse - approve", "Response to SignDataRequest",
|
|
&core.SignDataResponse{Approved: true})
|
|
add("SignDataResponse - deny", "Response to SignDataRequest",
|
|
&core.SignDataResponse{})
|
|
}
|
|
{ // Sign transaction request
|
|
desc := "SignTxRequest contains information about a pending request to sign a transaction. " +
|
|
"Aside from the transaction itself, there is also a `call_info`-struct. That struct contains " +
|
|
"messages of various types, that the user should be informed of." +
|
|
"\n\n" +
|
|
"As in any request, it's important to consider that the `meta` info also contains untrusted data." +
|
|
"\n\n" +
|
|
"The `transaction` (on input into clef) can have either `data` or `input` -- if both are set, " +
|
|
"they must be identical, otherwise an error is generated. " +
|
|
"However, Clef will always use `data` when passing this struct on (if Clef does otherwise, please file a ticket)"
|
|
|
|
data := hexutil.Bytes([]byte{0x01, 0x02, 0x03, 0x04})
|
|
add("SignTxRequest", desc, &core.SignTxRequest{
|
|
Meta: meta,
|
|
Callinfo: []apitypes.ValidationInfo{
|
|
{Typ: "Warning", Message: "Something looks odd, show this message as a warning"},
|
|
{Typ: "Info", Message: "User should see this as well"},
|
|
},
|
|
Transaction: apitypes.SendTxArgs{
|
|
Data: &data,
|
|
Nonce: 0x1,
|
|
Value: hexutil.Big(*big.NewInt(6)),
|
|
From: common.NewMixedcaseAddress(a),
|
|
To: nil,
|
|
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
|
Gas: 1000,
|
|
Input: nil,
|
|
}})
|
|
}
|
|
{ // Sign tx response
|
|
data := hexutil.Bytes([]byte{0x04, 0x03, 0x02, 0x01})
|
|
add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+
|
|
", because the UI is free to make modifications to the transaction.",
|
|
&core.SignTxResponse{Approved: true,
|
|
Transaction: apitypes.SendTxArgs{
|
|
Data: &data,
|
|
Nonce: 0x4,
|
|
Value: hexutil.Big(*big.NewInt(6)),
|
|
From: common.NewMixedcaseAddress(a),
|
|
To: nil,
|
|
GasPrice: (*hexutil.Big)(big.NewInt(5)),
|
|
Gas: 1000,
|
|
Input: nil,
|
|
}})
|
|
add("SignTxResponse - deny", "Response to SignTxRequest. When denying a request, there's no need to "+
|
|
"provide the transaction in return",
|
|
&core.SignTxResponse{})
|
|
}
|
|
{ // WHen a signed tx is ready to go out
|
|
desc := "SignTransactionResult is used in the call `clef` -> `OnApprovedTx(result)`" +
|
|
"\n\n" +
|
|
"This occurs _after_ successful completion of the entire signing procedure, but right before the signed " +
|
|
"transaction is passed to the external caller. This method (and data) can be used by the UI to signal " +
|
|
"to the user that the transaction was signed, but it is primarily useful for ruleset implementations." +
|
|
"\n\n" +
|
|
"A ruleset that implements a rate limitation needs to know what transactions are sent out to the external " +
|
|
"interface. By hooking into this methods, the ruleset can maintain track of that count." +
|
|
"\n\n" +
|
|
"**OBS:** Note that if an attacker can restore your `clef` data to a previous point in time" +
|
|
" (e.g through a backup), the attacker can reset such windows, even if he/she is unable to decrypt the content. " +
|
|
"\n\n" +
|
|
"The `OnApproved` method cannot be responded to, it's purely informative"
|
|
|
|
rlpdata := common.FromHex("0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed")
|
|
|
|
var tx types.Transaction
|
|
|
|
tx.UnmarshalBinary(rlpdata)
|
|
add("OnApproved - SignTransactionResult", desc, ðapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})
|
|
}
|
|
{ // User input
|
|
add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)",
|
|
&core.UserInputRequest{IsPassword: true, Title: "The title here", Prompt: "The question to ask the user"})
|
|
add("UserInputResponse", "Response to UserInputRequest",
|
|
&core.UserInputResponse{Text: "The textual response from user"})
|
|
}
|
|
{ // List request
|
|
add("ListRequest", "Sent when a request has been made to list addresses. The UI is provided with the "+
|
|
"full `account`s, including local directory names. Note: this information is not passed back to the external caller, "+
|
|
"who only sees the `address`es. ",
|
|
&core.ListRequest{
|
|
Meta: meta,
|
|
Accounts: []accounts.Account{
|
|
{Address: a, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
|
|
{Address: b, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
|
|
})
|
|
|
|
add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+
|
|
"Note: the UI is free to respond with any address the caller, regardless of whether it exists or not",
|
|
&core.ListResponse{
|
|
Accounts: []accounts.Account{
|
|
{
|
|
Address: common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"),
|
|
URL: accounts.URL{Path: ".. ignored .."},
|
|
},
|
|
{
|
|
Address: common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"),
|
|
},
|
|
}})
|
|
}
|
|
|
|
fmt.Println(`## UI Client interface
|
|
|
|
These data types are defined in the channel between clef and the UI`)
|
|
|
|
for _, elem := range output {
|
|
fmt.Println(elem)
|
|
}
|
|
|
|
return nil
|
|
}
|