mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-01 17:43:45 +00:00
* cmd, core, trie: verkle-capable `geth init` (#28270) This change allows the creation of a genesis block for verkle testnets. This makes for a chunk of code that is easier to review and still touches many discussion points. * eth/tracers/js: fix isPush for push0 (#28520) Fixes so that `push0` opcode is correctly reported as `true` by the `IsPush` function --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * trie: spelling - fix comments in hasher (#28507) Co-authored-by: VM <arimas@foxmail.com> * tests/fuzzers: move fuzzers into native packages (#28467) This PR moves our fuzzers from tests/fuzzers into whatever their respective 'native' package is. The historical reason why they were placed in an external location, is that when they were based on go-fuzz, they could not be "hidden" via the _test.go prefix. So in order to shove them away from the go-ethereum "production code", they were put aside. But now we've rewritten them to be based on golang testing, and thus can be brought back. I've left (in tests/) the ones that are not production (bls128381), require non-standard imports (secp requires btcec, bn256 requires gnark/google/cloudflare deps). This PR also adds a fuzzer for precompiled contracts, because why not. This PR utilizes a newly rewritten replacement for go-118-fuzz-build, namely gofuzz-shim, which utilises the inputs from the fuzzing engine better. * tests: skip tests on windows 32bit CI (#28521) tests: skip half the blockchain- and state-tests on windows 32bit CI-tests * cmd/geth: more special cases logging tests (#28527) adds logging tests for errors and custom fmt.Stringer-types which output strings that needs to be quoted/escaped. * accounts,cmd,console,les,metrics: refactor some errors checked by (ST1005) go-staticcheck (#28532) fix: fix some (ST1005)go-staticcheck * miner: run tests in parallel (#28506) Changes many of the tests in the miner package to run in parallel * internal/jsre/deps: fix typo in jsdoc (#28511) minor typo fix * accounts/abi: improve readability of method-to-string conversion (#28530) refactor: improve readability of NewMethod print * all: replace some cases of strings.SplitN with strings.Cut (#28446) * ethdb/memorydb, trie: reduced allocations (#28473) * trie: use pooling of iterator states in iterator The node iterator burns through a lot of memory while iterating a trie, and a lot of that can be avoided by using a fairly small pool (max 40 items). name old time/op new time/op delta Iterator-8 6.22ms ± 3% 5.40ms ± 6% -13.18% (p=0.008 n=5+5) name old alloc/op new alloc/op delta Iterator-8 2.36MB ± 0% 1.67MB ± 0% -29.23% (p=0.008 n=5+5) name old allocs/op new allocs/op delta Iterator-8 37.0k ± 0% 29.8k ± 0% ~ (p=0.079 n=4+5) * ethdb/memorydb: avoid one copying of key By making the transformation from []byte to string at an earlier point, we save an allocation which otherwise happens later on. name old time/op new time/op delta BatchAllocs-8 412µs ± 6% 382µs ± 2% -7.18% (p=0.016 n=5+4) name old alloc/op new alloc/op delta BatchAllocs-8 480kB ± 0% 490kB ± 0% +1.93% (p=0.008 n=5+5) name old allocs/op new allocs/op delta BatchAllocs-8 3.03k ± 0% 2.03k ± 0% -32.98% (p=0.008 n=5+5) * Dockerfile: update Go to 1.21 (#28538) * cmd/evm: validate blockchain tests poststate account storage (#28443) This PR verifies the accounts' storage as specified in a blockchain test's postState field The expect-section, it does really only check that the test works. It's meant for the test-author to verify that "If the test does what it's supposed to, then the nonce of X should be 2, and the slot Y at Z should be 0x123. This expect-section is not exhaustive (not full post-state) It is also not auto-generated, but put there manually by the author. We can still check it, as a test-sanity-check, in geth * signer: run tests in parallel (#28536) marks tests as parallel-safe in package signer * accounts, cmd: fix typos (#28526) * core/txpool/legacypool: respect nolocals-setting (#28435) This change adds a check to ensure that transactions added to the legacy pool are not treated as 'locals' if the global locals-management has been disabled. This change makes the pool enforce the --txpool.pricelimit setting. * cmd: run tests in parallel (#28546) * core/state/snapshot: print correct error from trie iterator (#28560) * cmd/evm: capitalize evm commands (#28569) * standard:fix for a unified standard * standard:fix more as a complements --------- Co-authored-by: haotian <haotian@haotiandeMacBook-Air.local> * accounts/abi: context info on unpack-errors (#28529) adds contextual information to errors returned by unpack * core, trie, rpc: speed up tests (#28461) * rpc: make subscription test faster reduces time for TestClientSubscriptionChannelClose from 25 sec to < 1 sec. * trie: cache trie nodes for faster sanity check This reduces the time spent on TestIncompleteSyncHash from ~25s to ~16s. * core/forkid: speed up validation test This takes the validation test from > 5s to sub 1 sec * core/state: improve snapshot test run brings the time for TestSnapshotRandom from 13s down to 6s * accounts/keystore: improve keyfile test This removes some unnecessary waits and reduces the runtime of TestUpdatedKeyfileContents from 5 to 3 seconds * trie: remove resolver * trie: only check ~5% of all trie nodes * ethdb/pebble: don't double-close iterator inside pebbleIterator (#28566) Adds 'released' flag to pebbleIterator to avoid double closing cockroachdb/pebble.Iterator as it is an invalid operation. Fixes #28565 * eth/filters: reuse error msg for invalid block range (#28479) * core/types: make 'v' optional for DynamicFeeTx and BlobTx (#28564) This fixes an issue where transactions would not be accepted when they have only 'yParity' and not 'v'. * rpc: improve performance of subscription notification encoding (#28328) It turns out that encoding json.RawMessage is slow because package json basically parses the message again to ensure it is valid. We can avoid the slowdown by encoding the entire RPC notification once, which yields a 30% speedup. * cmd/utils: validate pre-existing genesis in --dev mode (#28468) geth --dev can be used with an existing data directory and genesis block. Since dev mode only works with PoS, we need to verify that the merge has happened. Co-authored-by: Felix Lange <fjl@twurst.com> * cmd/geth: add support for --dev flag in dumpgenesis (#28463) Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: lightclient <lightclient@protonmail.com> * les/vflux: run tests in parallel (#28524) * cmd/{geth,utils}: add cmd to export preimages in snap enumeration order (#28256) Adds a subcommand: `geth snapshot export-preimages`, to export preimages of every hash found during a snapshot enumeration: that is, it exports _only the active state_, and not _all_ preimages that have been used but are no longer part of the state. This tool is needed for the verkle transition, in order to distribute the preimages needed for the conversion. Since only the 'active' preimages are exported, the output is shrunk from ~70GB to ~4GB. The order of the output is the order used by the snapshot enumeration, which avoids database thrashing. However, it also means that storage-slot preimages are not deduplicated. * cmd/geth: fix build error (#28585) * cmd/devp2p/internal/ethtest: undo debug-hack (#28588) cmd/devp2p/internal/ethtest: remove a debug-hack flaw which prevented certain tests from running * params: update discV5 bootnodes (#28562) update discV5 bootnodes from https://github.com/eth-clients/eth2-networks/blob/master/shared/mainnet/bootstrap_nodes.txt * cmd, les, tests: remove light client code (#28586) * cmd, les, tests: remove light client code This commit removes the light client (LES) code. Since the merge the light client has been broken and it is hard to maintain it alongside the normal client. We decided it would be best to remove it for now and maybe rework and reintroduce it in the future. * cmd, eth: remove some more mentions of light mode * cmd: re-add flags and mark as deprecated * cmd: warn the user about deprecated flags * eth: better error message * eth, internal/ethapi: drop some weird indirection (#28597) * trie: fix random test generator early terminate (#28590) This change fixes a minor bug in the `randTest.Generate` function, which caused the `quick.Check` to be a no-op. * eth/gasestimator, internal/ethapi: move gas estimator out of rpc (#28600) * go.mod: update uint256 to v1.2.4 (#28612) * eth/catalyst, eth/downloader: expose more sync information (#28584) This change exposes more information from sync module internally * light: remove package light(#28614) This changes removes the package 'light', which is currently unused. * cmd/evm, core/state: fix post-exec dump of state (statetests, blockchaintests) (#28504) There were several problems related to dumping state. - If a preimage was missing, even if we had set the `OnlyWithAddresses` to `false`, to export them anyway, the way the mapping was constructed (using `common.Address` as key) made the entries get lost anyway. Concerns both state- and blockchain tests. - Blockchain test execution was not configured to store preimages. This changes makes it so that the block test executor takes a callback, just like the state test executor already does. This callback can be used to examine the post-execution state, e.g. to aid debugging of test failures. * ethereum: remove TODO comment about subscription (#28609) * eth/tracers/js: fix type inconsistencies (#28488) This change fixes two type-inconsistencies in the JS tracer: - In most places we return byte arrays as a `Uint8Array` to the tracer. However it seems we missed doing the conversion for `ctx` fields which are passed to the tracer during `result`. They are passed as simple arrays. I think Uint8Arrays are more suitable and we should change this inconsistency. Note: this will be a breaking-change. But I believe the effect is small. If we look at our tracers we see that these fields (`ctx.from`, `ctx.to`, etc.) are used in 2 ways. Passed to `toHex` which takes both array or buffer. Or the length was measured which is the same for both types. - The `slice` taking in `int, int` params versus `memory.slice` taking `int64, int64` params. I suggest changing `slice` types to `int64`. This should have no effect almost in any case. * crypto/secp256k1: fix 32-bit tests when CGO_ENABLED=0 (#28602) * consensus: verify the nonexistence of shanghai- and cancun-specific header fields (#28605) * eth/gasestimator: allow slight estimation error in favor of less iterations (#28618) * eth/gasestimator: early exit for plain transfer and error allowance * core, eth/gasestimator: hard guess at a possible required gas * internal/ethapi: update estimation tests with the error ratio * eth/gasestimator: I hate you linter * graphql: fix gas estimation test --------- Co-authored-by: Oren <orenyomtov@users.noreply.github.com> * all: replace log15 with slog (#28187) This PR replaces Geth's logger package (a fork of [log15](https://github.com/inconshreveable/log15)) with an implementation using slog, a logging library included as part of the Go standard library as of Go1.21. Main changes are as follows: * removes any log handlers that were unused in the Geth codebase. * Json, logfmt, and terminal formatters are now slog handlers. * Verbosity level constants are changed to match slog constant values. Internal translation is done to make this opaque to the user and backwards compatible with existing `--verbosity` and `--vmodule` options. * `--log.backtraceat` and `--log.debug` are removed. The external-facing API is largely the same as the existing Geth logger. Logger method signatures remain unchanged. A small semantic difference is that a `Handler` can only be set once per `Logger` and not changed dynamically. This just means that a new logger must be instantiated every time the handler of the root logger is changed. ---- For users of the `go-ethereum/log` module. If you were using this module for your own project, you will need to change the initialization. If you previously did ```golang log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) ``` You now instead need to do ```golang log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelInfo, true))) ``` See more about reasoning here: https://github.com/ethereum/go-ethereum/issues/28558#issuecomment-1820606613 * core/state: make stateobject.create selfcontain (#28459) * trie/triedb/hashdb: take lock around access to dirties cache (#28542) Add read locking of db lock around access to dirties cache in hashdb.Database to prevent data race versus hashdb.Database.dereference which can modify the dirities map by deleting an item. Fixes #28541 --------- Co-authored-by: Gary Rong <garyrong0905@gmail.com> * accounts/abi/bind: fix typo (#28630) * slog: faster and less memory-consumption (#28621) These changes improves the performance of the non-coloured terminal formatting, _quite a lot_. ``` name old time/op new time/op delta TerminalHandler-8 10.2µs ±15% 5.4µs ± 9% -47.02% (p=0.008 n=5+5) name old alloc/op new alloc/op delta TerminalHandler-8 2.17kB ± 0% 0.40kB ± 0% -81.46% (p=0.008 n=5+5) name old allocs/op new allocs/op delta TerminalHandler-8 33.0 ± 0% 5.0 ± 0% -84.85% (p=0.008 n=5+5) ``` I tried to _somewhat_ organize the commits, but the it might still be a bit chaotic. Some core insights: - The function `terminalHandler.Handl` uses a mutex, and writes all output immediately to 'upstream'. Thus, it can reuse a scratch-buffer every time. - This buffer can be propagated internally, making all the internal formatters either write directly to it, - OR, make use of the `tmp := buf.AvailableBuffer()` in some cases, where a byte buffer "extra capacity" can be temporarily used. - The `slog` package uses `Attr` by value. It makes sense to minimize operating on them, since iterating / collecting into a new slice, iterating again etc causes copy-on-heap. Better to operate on them only once. - If we want to do padding, it's better to copy from a constant `space`-buffer than to invoke `bytes.Repeat` every single time. * eth/tracers: tx-level state in debug_traceCall (#28460) * cmd/evm: fix Env struct json tag (#28635) * accounts/abi/bind: fixed typos (#28634) * Update auth.go * Update backend.go * Update bind.go * Update bind_test.go * eth/fetcher: fix invalid tracking of received at time for block (#28637) eth/fetcher: fix invalid tracking of received at time * accounts: run tests in parallel (#28544) * eth/tracers/logger: make structlog/json-log stack hex again (#28628) * common/hexutil: define hex wrappers for uint256.Int * eth/tracers/logger: make structlog/json-log stack hex again * common/hexutil: goimports * log: remove lazy, remove unused interfaces, unexport methods (#28622) This change - Removes interface `log.Format`, - Removes method `log.FormatFunc`, - unexports `TerminalHandler.TerminalFormat` formatting methods (renamed to `TerminalHandler.format`) - removes the notion of `log.Lazy` values The lazy handler was useful in the old log package, since it could defer the evaluation of costly attributes until later in the log pipeline: thus, if the logging was done at 'Trace', we could skip evaluation if logging only was set to 'Info'. With the move to slog, this way of deferring evaluation is no longer needed, since slog introduced 'Enabled': the caller can thus do the evaluate-or-not decision at the callsite, which is much more straight-forward than dealing with lazy reflect-based evaluation. Also, lazy evaluation would not work with 'native' slog, as in, these two statements would be evaluated differently: ```golang log.Info("foo", "my lazy", lazyObj) slog.Info("foo", "my lazy", lazyObj) ``` * .github: use github actions to run 32-bit linux tests (#28549) use github actions to run 32-bit linux tests * ethdb/pebble: remove a dependency (#28627) The dependency was not really used anyway, so we can get rid of it. Co-authored-by: Felix Lange <fjl@twurst.com> * tests/fuzzers/bls12381: deactivate BLS fuzzer when CGO_ENABLED=0 (#28653) tests/fuzzers/bls12381: deactivate fuzzer when CGO_ENABLED=0 * build: upgrade -dlgo version to Go 1.21.5 (#28648) * rpc: fix ns/µs mismatch in metrics (#28649) The rpc/duration/all meter was in nanoseconds, the individual meter in microseconds. This PR changes it so both of them use nanoseconds. * cmd/evm: fix dump after state-test exec (#28650) The dump after state-test didn't work, the problem was an error, "Already committed", which was silently ignored. This change re-initialises the state, so the dumping works again. * beacon/light: add CommitteeChain (#27766) This change implements CommitteeChain which is a key component of the beacon light client. It is a passive data structure that can validate, hold and update a chain of beacon light sync committees and updates, starting from a checkpoint that proves the starting committee through a beacon block hash, header and corresponding state. Once synced to the current sync period, CommitteeChain can also validate signed beacon headers. * cmd/utils, eth: disallow invalid snap sync / snapshot flag combos (#28657) * eth: prevent startup in snap mode without snapshots * cmd/utils: try to fix bad flag combos wrt snap sync and snapshot generation * trie: remove inconsistent trie nodes during sync in path mode (#28595) This fixes a database corruption issue that could occur during state healing. When sync is aborted while certain modifications were already committed, and a reorg occurs, the database would contain incorrect trie nodes stored by path. These nodes need to detected/deleted in order to obtain a complete and fully correct state after state healing. --------- Co-authored-by: Felix Lange <fjl@twurst.com> * cmd/utils: fix HTTPHost, WSHost flag priority (#28669) Co-authored-by: Felix Lange <fjl@twurst.com> * eth/protocols/eth: fix typos in comments (#28652) * core/txpool : small cleanup refactors (#28654) * eth/fetcher, eth/gasestimator: fix typos in comments (#28675) * all: fix typos in comments (#28662) Co-authored-by: Felix Lange <fjl@twurst.com> * miner: eliminate the dead loop possibility for `newWorkLoop` and `mainLoop` (#28677) discard the intervalAdjust message if the channel is full * all: fix typos in comments (#28682) chore(core,eth):fix a couple of typos * p2p/discover: add liveness check in collectTableNodes (#28686) * p2p/discover: add liveness check in collectTableNodes * p2p/discover: fix test * p2p/discover: rename to appendLiveNodes * p2p/discover: add dedup logic back * p2p/discover: simplify * p2p/discover: fix issue found by test * internal/flags: add missing flag types for auto-env-var generation (#28692) Certain flags, such as `--rpc.txfeecap` currently do not have an env-var auto-generated for them. This change adds three missing cli flag types to the auto env-var helper function to fix this. * cmd/evm: default to mirror mainnet forks enabled (#28691) cmd/evm: default to using dev chain config (all mainnet HFs activated at block/timestamp 0 * cmd/evm, cmd/clef, cmd/bootnode: fix / unify logging (#28696) This change fixes a problem with our non-core binaries: evm, clef, bootnode. First of all, they failed to convert from legacy loglevels 1 to 5, to the new slog loglevels -4 to 4. Secondly, the logging was actually setup in the init phase, and then overridden in the main. This is not needed for evm, since it used the same flag name as the main geth verbosity. Better to let the flags/internal handle the logging init. * cmd/evm: t8n support custom tracers (#28557) This change implements ability for the `evm t8n` tool to use custom tracers; either 'native' golang tracers or javascript tracers. * params: release go-ethereum v1.13.6 stable * Fix build errors * Fix test-integration --------- Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: VM <112189277+sysvm@users.noreply.github.com> Co-authored-by: VM <arimas@foxmail.com> Co-authored-by: jwasinger <j-wasinger@hotmail.com> Co-authored-by: Zoro <40222601+BabyHalimao@users.noreply.github.com> Co-authored-by: Håvard Anda Estensen <haavard.ae@gmail.com> Co-authored-by: aliening <128203330+aliening@users.noreply.github.com> Co-authored-by: Halimao <1065621723@qq.com> Co-authored-by: danceratopz <danceratopz@gmail.com> Co-authored-by: levisyin <150114626+levisyin@users.noreply.github.com> Co-authored-by: jp-imx <109574657+jp-imx@users.noreply.github.com> Co-authored-by: rjl493456442 <garyrong0905@gmail.com> Co-authored-by: Haotian <51777534+tmelhao@users.noreply.github.com> Co-authored-by: haotian <haotian@haotiandeMacBook-Air.local> Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> Co-authored-by: Maciej Kulawik <10907694+magicxyyz@users.noreply.github.com> Co-authored-by: ucwong <ucwong@126.com> Co-authored-by: Mario Vega <marioevz@gmail.com> Co-authored-by: Delweng <delweng@gmail.com> Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: lightclient <lightclient@protonmail.com> Co-authored-by: Mikel Cortes <45786396+cortze@users.noreply.github.com> Co-authored-by: Péter Szilágyi <peterke@gmail.com> Co-authored-by: Ng Wei Han <47109095+weiihann@users.noreply.github.com> Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com> Co-authored-by: Shivam Sandbhor <shivam.sandbhor@gmail.com> Co-authored-by: Jakub Freebit <49676311+jakub-freebit@users.noreply.github.com> Co-authored-by: Oren <orenyomtov@users.noreply.github.com> Co-authored-by: BorkBorked <107079055+BorkBorked@users.noreply.github.com> Co-authored-by: ddl <dengdiliang@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Marius Kjærstad <sandakersmann@users.noreply.github.com> Co-authored-by: Felföldi Zsolt <zsfelfoldi@gmail.com> Co-authored-by: Ford <153042616+guerrierindien@users.noreply.github.com> Co-authored-by: Ursulafe <152976968+Ursulafe@users.noreply.github.com> Co-authored-by: Elias Rad <146735585+nnsW3@users.noreply.github.com> Co-authored-by: FletcherMan <fanciture@163.com> Co-authored-by: alex <152680487+bodhi-crypo@users.noreply.github.com> Co-authored-by: Sebastian Stammler <seb@oplabs.co>
1151 lines
35 KiB
Go
1151 lines
35 KiB
Go
// Copyright 2018 The go-ethereum Authors
|
|
// This file is part of the go-ethereum library.
|
|
//
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU Lesser General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
package scwallet
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"crypto/sha512"
|
|
"encoding/asn1"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/ethereum/go-ethereum"
|
|
"github.com/ethereum/go-ethereum/accounts"
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
"github.com/ethereum/go-ethereum/log"
|
|
pcsc "github.com/gballet/go-libpcsclite"
|
|
"github.com/status-im/keycard-go/derivationpath"
|
|
)
|
|
|
|
// ErrPairingPasswordNeeded is returned if opening the smart card requires pairing with a pairing
|
|
// password. In this case, the calling application should request user input to enter
|
|
// the pairing password and send it back.
|
|
var ErrPairingPasswordNeeded = errors.New("smartcard: pairing password needed")
|
|
|
|
// ErrPINNeeded is returned if opening the smart card requires a PIN code. In
|
|
// this case, the calling application should request user input to enter the PIN
|
|
// and send it back.
|
|
var ErrPINNeeded = errors.New("smartcard: pin needed")
|
|
|
|
// ErrPINUnblockNeeded is returned if opening the smart card requires a PIN code,
|
|
// but all PIN attempts have already been exhausted. In this case the calling
|
|
// application should request user input for the PUK and a new PIN code to set
|
|
// fo the card.
|
|
var ErrPINUnblockNeeded = errors.New("smartcard: pin unblock needed")
|
|
|
|
// ErrAlreadyOpen is returned if the smart card is attempted to be opened, but
|
|
// there is already a paired and unlocked session.
|
|
var ErrAlreadyOpen = errors.New("smartcard: already open")
|
|
|
|
// ErrPubkeyMismatch is returned if the public key recovered from a signature
|
|
// does not match the one expected by the user.
|
|
var ErrPubkeyMismatch = errors.New("smartcard: recovered public key mismatch")
|
|
|
|
var (
|
|
appletAID = []byte{0xA0, 0x00, 0x00, 0x08, 0x04, 0x00, 0x01, 0x01, 0x01}
|
|
// DerivationSignatureHash is used to derive the public key from the signature of this hash
|
|
DerivationSignatureHash = sha256.Sum256(common.Hash{}.Bytes())
|
|
)
|
|
|
|
// List of APDU command-related constants
|
|
const (
|
|
claISO7816 = 0
|
|
claSCWallet = 0x80
|
|
|
|
insSelect = 0xA4
|
|
insGetResponse = 0xC0
|
|
sw1GetResponse = 0x61
|
|
sw1Ok = 0x90
|
|
|
|
insVerifyPin = 0x20
|
|
insUnblockPin = 0x22
|
|
insExportKey = 0xC2
|
|
insSign = 0xC0
|
|
insLoadKey = 0xD0
|
|
insDeriveKey = 0xD1
|
|
insStatus = 0xF2
|
|
)
|
|
|
|
// List of ADPU command parameters
|
|
const (
|
|
P1DeriveKeyFromMaster = uint8(0x00)
|
|
P1DeriveKeyFromParent = uint8(0x01)
|
|
P1DeriveKeyFromCurrent = uint8(0x10)
|
|
statusP1WalletStatus = uint8(0x00)
|
|
statusP1Path = uint8(0x01)
|
|
signP1PrecomputedHash = uint8(0x00)
|
|
signP2OnlyBlock = uint8(0x00)
|
|
exportP1Any = uint8(0x00)
|
|
exportP2Pubkey = uint8(0x01)
|
|
)
|
|
|
|
// Minimum time to wait between self derivation attempts, even it the user is
|
|
// requesting accounts like crazy.
|
|
const selfDeriveThrottling = time.Second
|
|
|
|
// Wallet represents a smartcard wallet instance.
|
|
type Wallet struct {
|
|
Hub *Hub // A handle to the Hub that instantiated this wallet.
|
|
PublicKey []byte // The wallet's public key (used for communication and identification, not signing!)
|
|
|
|
lock sync.Mutex // Lock that gates access to struct fields and communication with the card
|
|
card *pcsc.Card // A handle to the smartcard interface for the wallet.
|
|
session *Session // The secure communication session with the card
|
|
log log.Logger // Contextual logger to tag the base with its id
|
|
|
|
deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported)
|
|
deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported)
|
|
deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
|
|
deriveReq chan chan struct{} // Channel to request a self-derivation on
|
|
deriveQuit chan chan error // Channel to terminate the self-deriver with
|
|
}
|
|
|
|
// NewWallet constructs and returns a new Wallet instance.
|
|
func NewWallet(hub *Hub, card *pcsc.Card) *Wallet {
|
|
wallet := &Wallet{
|
|
Hub: hub,
|
|
card: card,
|
|
}
|
|
|
|
return wallet
|
|
}
|
|
|
|
// transmit sends an APDU to the smartcard and receives and decodes the response.
|
|
// It automatically handles requests by the card to fetch the return data separately,
|
|
// and returns an error if the response status code is not success.
|
|
func transmit(card *pcsc.Card, command *commandAPDU) (*responseAPDU, error) {
|
|
data, err := command.serialize()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
responseData, _, err := card.Transmit(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
response := new(responseAPDU)
|
|
if err = response.deserialize(responseData); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Are we being asked to fetch the response separately?
|
|
if response.Sw1 == sw1GetResponse && (command.Cla != claISO7816 || command.Ins != insGetResponse) {
|
|
return transmit(card, &commandAPDU{
|
|
Cla: claISO7816,
|
|
Ins: insGetResponse,
|
|
P1: 0,
|
|
P2: 0,
|
|
Data: nil,
|
|
Le: response.Sw2,
|
|
})
|
|
}
|
|
|
|
if response.Sw1 != sw1Ok {
|
|
return nil, fmt.Errorf("unexpected insecure response status Cla=%#x, Ins=%#x, Sw=%#x%x", command.Cla, command.Ins, response.Sw1, response.Sw2)
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
// applicationInfo encodes information about the smartcard application - its
|
|
// instance UID and public key.
|
|
type applicationInfo struct {
|
|
InstanceUID []byte `asn1:"tag:15"`
|
|
PublicKey []byte `asn1:"tag:0"`
|
|
}
|
|
|
|
// connect connects to the wallet application and establishes a secure channel with it.
|
|
// must be called before any other interaction with the wallet.
|
|
func (w *Wallet) connect() error {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
appinfo, err := w.doselect()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
channel, err := NewSecureChannelSession(w.card, appinfo.PublicKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
w.PublicKey = appinfo.PublicKey
|
|
w.log = log.New("url", w.URL())
|
|
w.session = &Session{
|
|
Wallet: w,
|
|
Channel: channel,
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// doselect is an internal (unlocked) function to send a SELECT APDU to the card.
|
|
func (w *Wallet) doselect() (*applicationInfo, error) {
|
|
response, err := transmit(w.card, &commandAPDU{
|
|
Cla: claISO7816,
|
|
Ins: insSelect,
|
|
P1: 4,
|
|
P2: 0,
|
|
Data: appletAID,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
appinfo := new(applicationInfo)
|
|
if _, err := asn1.UnmarshalWithParams(response.Data, appinfo, "tag:4"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return appinfo, nil
|
|
}
|
|
|
|
// ping checks the card's status and returns an error if unsuccessful.
|
|
func (w *Wallet) ping() error {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
// We can't ping if not paired
|
|
if !w.session.paired() {
|
|
return nil
|
|
}
|
|
|
|
if _, err := w.session.walletStatus(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// release releases any resources held by an open wallet instance.
|
|
func (w *Wallet) release() error {
|
|
if w.session != nil {
|
|
return w.session.release()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// pair is an internal (unlocked) function for establishing a new pairing
|
|
// with the wallet.
|
|
func (w *Wallet) pair(puk []byte) error {
|
|
if w.session.paired() {
|
|
return errors.New("wallet already paired")
|
|
}
|
|
|
|
pairing, err := w.session.pair(puk)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = w.Hub.setPairing(w, &pairing); err != nil {
|
|
return err
|
|
}
|
|
|
|
return w.session.authenticate(pairing)
|
|
}
|
|
|
|
// Unpair deletes an existing wallet pairing.
|
|
func (w *Wallet) Unpair(pin []byte) error {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
if !w.session.paired() {
|
|
return fmt.Errorf("wallet %x not paired", w.PublicKey)
|
|
}
|
|
|
|
if err := w.session.verifyPin(pin); err != nil {
|
|
return fmt.Errorf("failed to verify pin: %s", err)
|
|
}
|
|
|
|
if err := w.session.unpair(); err != nil {
|
|
return fmt.Errorf("failed to unpair: %s", err)
|
|
}
|
|
|
|
if err := w.Hub.setPairing(w, nil); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// URL retrieves the canonical path under which this wallet is reachable. It is
|
|
// user by upper layers to define a sorting order over all wallets from multiple
|
|
// backends.
|
|
func (w *Wallet) URL() accounts.URL {
|
|
return accounts.URL{
|
|
Scheme: w.Hub.scheme,
|
|
Path: fmt.Sprintf("%x", w.PublicKey[1:5]), // Byte #0 isn't unique; 1:5 covers << 64K cards, bump to 1:9 for << 4M
|
|
}
|
|
}
|
|
|
|
// Status returns a textual status to aid the user in the current state of the
|
|
// wallet. It also returns an error indicating any failure the wallet might have
|
|
// encountered.
|
|
func (w *Wallet) Status() (string, error) {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
// If the card is not paired, we can only wait
|
|
if !w.session.paired() {
|
|
return "Unpaired, waiting for pairing password", nil
|
|
}
|
|
// Yay, we have an encrypted session, retrieve the actual status
|
|
status, err := w.session.walletStatus()
|
|
if err != nil {
|
|
return fmt.Sprintf("Failed: %v", err), err
|
|
}
|
|
|
|
switch {
|
|
case !w.session.verified && status.PinRetryCount == 0 && status.PukRetryCount == 0:
|
|
return "Bricked, waiting for full wipe", nil
|
|
case !w.session.verified && status.PinRetryCount == 0:
|
|
return fmt.Sprintf("Blocked, waiting for PUK (%d attempts left) and new PIN", status.PukRetryCount), nil
|
|
case !w.session.verified:
|
|
return fmt.Sprintf("Locked, waiting for PIN (%d attempts left)", status.PinRetryCount), nil
|
|
case !status.Initialized:
|
|
return "Empty, waiting for initialization", nil
|
|
default:
|
|
return "Online", nil
|
|
}
|
|
}
|
|
|
|
// Open initializes access to a wallet instance. It is not meant to unlock or
|
|
// decrypt account keys, rather simply to establish a connection to hardware
|
|
// wallets and/or to access derivation seeds.
|
|
//
|
|
// The passphrase parameter may or may not be used by the implementation of a
|
|
// particular wallet instance. The reason there is no passwordless open method
|
|
// is to strive towards a uniform wallet handling, oblivious to the different
|
|
// backend providers.
|
|
//
|
|
// Please note, if you open a wallet, you must close it to release any allocated
|
|
// resources (especially important when working with hardware wallets).
|
|
func (w *Wallet) Open(passphrase string) error {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
// If the session is already open, bail out
|
|
if w.session.verified {
|
|
return ErrAlreadyOpen
|
|
}
|
|
// If the smart card is not yet paired, attempt to do so either from a previous
|
|
// pairing key or form the supplied PUK code.
|
|
if !w.session.paired() {
|
|
// If a previous pairing exists, only ever try to use that
|
|
if pairing := w.Hub.pairing(w); pairing != nil {
|
|
if err := w.session.authenticate(*pairing); err != nil {
|
|
return fmt.Errorf("failed to authenticate card %x: %s", w.PublicKey[:4], err)
|
|
}
|
|
// Pairing still ok, fall through to PIN checks
|
|
} else {
|
|
// If no passphrase was supplied, request the PUK from the user
|
|
if passphrase == "" {
|
|
return ErrPairingPasswordNeeded
|
|
}
|
|
// Attempt to pair the smart card with the user supplied PUK
|
|
if err := w.pair([]byte(passphrase)); err != nil {
|
|
return err
|
|
}
|
|
// Pairing succeeded, fall through to PIN checks. This will of course fail,
|
|
// but we can't return ErrPINNeeded directly here because we don't know whether
|
|
// a PIN check or a PIN reset is needed.
|
|
passphrase = ""
|
|
}
|
|
}
|
|
// The smart card was successfully paired, retrieve its status to check whether
|
|
// PIN verification or unblocking is needed.
|
|
status, err := w.session.walletStatus()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Request the appropriate next authentication data, or use the one supplied
|
|
switch {
|
|
case passphrase == "" && status.PinRetryCount > 0:
|
|
return ErrPINNeeded
|
|
case passphrase == "":
|
|
return ErrPINUnblockNeeded
|
|
case status.PinRetryCount > 0:
|
|
if !regexp.MustCompile(`^[0-9]{6,}$`).MatchString(passphrase) {
|
|
w.log.Error("PIN needs to be at least 6 digits")
|
|
return ErrPINNeeded
|
|
}
|
|
|
|
if err := w.session.verifyPin([]byte(passphrase)); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
if !regexp.MustCompile(`^[0-9]{12,}$`).MatchString(passphrase) {
|
|
w.log.Error("PUK needs to be at least 12 digits")
|
|
return ErrPINUnblockNeeded
|
|
}
|
|
|
|
if err := w.session.unblockPin([]byte(passphrase)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
// Smart card paired and unlocked, initialize and register
|
|
w.deriveReq = make(chan chan struct{})
|
|
w.deriveQuit = make(chan chan error)
|
|
|
|
go w.selfDerive()
|
|
|
|
// Notify anyone listening for wallet events that a new device is accessible
|
|
go w.Hub.updateFeed.Send(accounts.WalletEvent{Wallet: w, Kind: accounts.WalletOpened})
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close stops and closes the wallet, freeing any resources.
|
|
func (w *Wallet) Close() error {
|
|
// Ensure the wallet was opened
|
|
w.lock.Lock()
|
|
dQuit := w.deriveQuit
|
|
w.lock.Unlock()
|
|
|
|
// Terminate the self-derivations
|
|
var derr error
|
|
|
|
if dQuit != nil {
|
|
errc := make(chan error)
|
|
dQuit <- errc
|
|
derr = <-errc // Save for later, we *must* close the USB
|
|
}
|
|
// Terminate the device connection
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
w.deriveQuit = nil
|
|
w.deriveReq = nil
|
|
|
|
if err := w.release(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return derr
|
|
}
|
|
|
|
// selfDerive is an account derivation loop that upon request attempts to find
|
|
// new non-zero accounts.
|
|
func (w *Wallet) selfDerive() {
|
|
w.log.Debug("Smart card wallet self-derivation started")
|
|
defer w.log.Debug("Smart card wallet self-derivation stopped")
|
|
|
|
// Execute self-derivations until termination or error
|
|
var (
|
|
reqc chan struct{}
|
|
errc chan error
|
|
err error
|
|
)
|
|
|
|
for errc == nil && err == nil {
|
|
// Wait until either derivation or termination is requested
|
|
select {
|
|
case errc = <-w.deriveQuit:
|
|
// Termination requested
|
|
continue
|
|
case reqc = <-w.deriveReq:
|
|
// Account discovery requested
|
|
}
|
|
// Derivation needs a chain and device access, skip if either unavailable
|
|
w.lock.Lock()
|
|
if w.session == nil || w.deriveChain == nil {
|
|
w.lock.Unlock()
|
|
reqc <- struct{}{}
|
|
|
|
continue
|
|
}
|
|
|
|
pairing := w.Hub.pairing(w)
|
|
|
|
// Device lock obtained, derive the next batch of accounts
|
|
var (
|
|
paths []accounts.DerivationPath
|
|
nextAcc accounts.Account
|
|
|
|
nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...)
|
|
nextAddrs = append([]common.Address{}, w.deriveNextAddrs...)
|
|
|
|
context = context.Background()
|
|
)
|
|
|
|
for i := 0; i < len(nextAddrs); i++ {
|
|
for empty := false; !empty; {
|
|
// Retrieve the next derived Ethereum account
|
|
if nextAddrs[i] == (common.Address{}) {
|
|
if nextAcc, err = w.session.derive(nextPaths[i]); err != nil {
|
|
w.log.Warn("Smartcard wallet account derivation failed", "err", err)
|
|
break
|
|
}
|
|
|
|
nextAddrs[i] = nextAcc.Address
|
|
}
|
|
// Check the account's status against the current chain state
|
|
var (
|
|
balance *big.Int
|
|
nonce uint64
|
|
)
|
|
|
|
balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil)
|
|
if err != nil {
|
|
w.log.Warn("Smartcard wallet balance retrieval failed", "err", err)
|
|
break
|
|
}
|
|
|
|
nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil)
|
|
if err != nil {
|
|
w.log.Warn("Smartcard wallet nonce retrieval failed", "err", err)
|
|
break
|
|
}
|
|
// If the next account is empty, stop self-derivation, but add for the last base path
|
|
if balance.Sign() == 0 && nonce == 0 {
|
|
empty = true
|
|
|
|
if i < len(nextAddrs)-1 {
|
|
break
|
|
}
|
|
}
|
|
// We've just self-derived a new account, start tracking it locally
|
|
path := make(accounts.DerivationPath, len(nextPaths[i]))
|
|
copy(path[:], nextPaths[i][:])
|
|
paths = append(paths, path)
|
|
|
|
// Display a log message to the user for new (or previously empty accounts)
|
|
if _, known := pairing.Accounts[nextAddrs[i]]; !known || !empty || nextAddrs[i] != w.deriveNextAddrs[i] {
|
|
w.log.Info("Smartcard wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce)
|
|
}
|
|
|
|
pairing.Accounts[nextAddrs[i]] = path
|
|
|
|
// Fetch the next potential account
|
|
if !empty {
|
|
nextAddrs[i] = common.Address{}
|
|
nextPaths[i][len(nextPaths[i])-1]++
|
|
}
|
|
}
|
|
}
|
|
// If there are new accounts, write them out
|
|
if len(paths) > 0 {
|
|
err = w.Hub.setPairing(w, pairing)
|
|
}
|
|
// Shift the self-derivation forward
|
|
w.deriveNextAddrs = nextAddrs
|
|
w.deriveNextPaths = nextPaths
|
|
|
|
// Self derivation complete, release device lock
|
|
w.lock.Unlock()
|
|
|
|
// Notify the user of termination and loop after a bit of time (to avoid trashing)
|
|
reqc <- struct{}{}
|
|
|
|
if err == nil {
|
|
select {
|
|
case errc = <-w.deriveQuit:
|
|
// Termination requested, abort
|
|
case <-time.After(selfDeriveThrottling):
|
|
// Waited enough, willing to self-derive again
|
|
}
|
|
}
|
|
}
|
|
// In case of error, wait for termination
|
|
if err != nil {
|
|
w.log.Debug("Smartcard wallet self-derivation failed", "err", err)
|
|
errc = <-w.deriveQuit
|
|
}
|
|
errc <- err
|
|
}
|
|
|
|
// Accounts retrieves the list of signing accounts the wallet is currently aware
|
|
// of. For hierarchical deterministic wallets, the list will not be exhaustive,
|
|
// rather only contain the accounts explicitly pinned during account derivation.
|
|
func (w *Wallet) Accounts() []accounts.Account {
|
|
// Attempt self-derivation if it's running
|
|
reqc := make(chan struct{}, 1)
|
|
select {
|
|
case w.deriveReq <- reqc:
|
|
// Self-derivation request accepted, wait for it
|
|
<-reqc
|
|
default:
|
|
// Self-derivation offline, throttled or busy, skip
|
|
}
|
|
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
if pairing := w.Hub.pairing(w); pairing != nil {
|
|
ret := make([]accounts.Account, 0, len(pairing.Accounts))
|
|
for address, path := range pairing.Accounts {
|
|
ret = append(ret, w.makeAccount(address, path))
|
|
}
|
|
|
|
sort.Sort(accounts.AccountsByURL(ret))
|
|
|
|
return ret
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (w *Wallet) makeAccount(address common.Address, path accounts.DerivationPath) accounts.Account {
|
|
return accounts.Account{
|
|
Address: address,
|
|
URL: accounts.URL{
|
|
Scheme: w.Hub.scheme,
|
|
Path: fmt.Sprintf("%x/%s", w.PublicKey[1:3], path.String()),
|
|
},
|
|
}
|
|
}
|
|
|
|
// Contains returns whether an account is part of this particular wallet or not.
|
|
func (w *Wallet) Contains(account accounts.Account) bool {
|
|
if pairing := w.Hub.pairing(w); pairing != nil {
|
|
_, ok := pairing.Accounts[account.Address]
|
|
return ok
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// Initialize installs a keypair generated from the provided key into the wallet.
|
|
func (w *Wallet) Initialize(seed []byte) error {
|
|
go w.selfDerive()
|
|
// DO NOT lock at this stage, as the initialize
|
|
// function relies on Status()
|
|
return w.session.initialize(seed)
|
|
}
|
|
|
|
// Derive attempts to explicitly derive a hierarchical deterministic account at
|
|
// the specified derivation path. If requested, the derived account will be added
|
|
// to the wallet's tracked account list.
|
|
func (w *Wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
account, err := w.session.derive(path)
|
|
if err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
if pin {
|
|
pairing := w.Hub.pairing(w)
|
|
pairing.Accounts[account.Address] = path
|
|
|
|
if err := w.Hub.setPairing(w, pairing); err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
}
|
|
|
|
return account, nil
|
|
}
|
|
|
|
// SelfDerive sets a base account derivation path from which the wallet attempts
|
|
// to discover non zero accounts and automatically add them to list of tracked
|
|
// accounts.
|
|
//
|
|
// Note, self derivation will increment the last component of the specified path
|
|
// opposed to descending into a child path to allow discovering accounts starting
|
|
// from non zero components.
|
|
//
|
|
// Some hardware wallets switched derivation paths through their evolution, so
|
|
// this method supports providing multiple bases to discover old user accounts
|
|
// too. Only the last base will be used to derive the next empty account.
|
|
//
|
|
// You can disable automatic account discovery by calling SelfDerive with a nil
|
|
// chain state reader.
|
|
func (w *Wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
w.deriveNextPaths = make([]accounts.DerivationPath, len(bases))
|
|
for i, base := range bases {
|
|
w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base))
|
|
copy(w.deriveNextPaths[i][:], base[:])
|
|
}
|
|
|
|
w.deriveNextAddrs = make([]common.Address, len(bases))
|
|
w.deriveChain = chain
|
|
}
|
|
|
|
// SignData requests the wallet to sign the hash of the given data.
|
|
//
|
|
// It looks up the account specified either solely via its address contained within,
|
|
// or optionally with the aid of any location metadata from the embedded URL field.
|
|
//
|
|
// If the wallet requires additional authentication to sign the request (e.g.
|
|
// a password to decrypt the account, or a PIN code o verify the transaction),
|
|
// an AuthNeededError instance will be returned, containing infos for the user
|
|
// about which fields or actions are needed. The user may retry by providing
|
|
// the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
|
|
// the account in a keystore).
|
|
func (w *Wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
|
|
return w.signHash(account, crypto.Keccak256(data))
|
|
}
|
|
|
|
func (w *Wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
|
|
w.lock.Lock()
|
|
defer w.lock.Unlock()
|
|
|
|
path, err := w.findAccountPath(account)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return w.session.sign(path, hash)
|
|
}
|
|
|
|
// SignTx requests the wallet to sign the given transaction.
|
|
//
|
|
// It looks up the account specified either solely via its address contained within,
|
|
// or optionally with the aid of any location metadata from the embedded URL field.
|
|
//
|
|
// If the wallet requires additional authentication to sign the request (e.g.
|
|
// a password to decrypt the account, or a PIN code o verify the transaction),
|
|
// an AuthNeededError instance will be returned, containing infos for the user
|
|
// about which fields or actions are needed. The user may retry by providing
|
|
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
|
|
// the account in a keystore).
|
|
func (w *Wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
|
signer := types.LatestSignerForChainID(chainID)
|
|
hash := signer.Hash(tx)
|
|
|
|
sig, err := w.signHash(account, hash[:])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return tx.WithSignature(signer, sig)
|
|
}
|
|
|
|
// SignDataWithPassphrase requests the wallet to sign the given hash with the
|
|
// given passphrase as extra authentication information.
|
|
//
|
|
// It looks up the account specified either solely via its address contained within,
|
|
// or optionally with the aid of any location metadata from the embedded URL field.
|
|
func (w *Wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
|
|
return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
|
|
}
|
|
|
|
func (w *Wallet) signHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
|
|
if !w.session.verified {
|
|
if err := w.Open(passphrase); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return w.signHash(account, hash)
|
|
}
|
|
|
|
// SignText requests the wallet to sign the hash of a given piece of data, prefixed
|
|
// by the Ethereum prefix scheme
|
|
// It looks up the account specified either solely via its address contained within,
|
|
// or optionally with the aid of any location metadata from the embedded URL field.
|
|
//
|
|
// If the wallet requires additional authentication to sign the request (e.g.
|
|
// a password to decrypt the account, or a PIN code o verify the transaction),
|
|
// an AuthNeededError instance will be returned, containing infos for the user
|
|
// about which fields or actions are needed. The user may retry by providing
|
|
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
|
|
// the account in a keystore).
|
|
func (w *Wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
|
|
return w.signHash(account, accounts.TextHash(text))
|
|
}
|
|
|
|
// SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
|
|
// given hash with the given account using passphrase as extra authentication
|
|
func (w *Wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
|
|
return w.signHashWithPassphrase(account, passphrase, crypto.Keccak256(accounts.TextHash(text)))
|
|
}
|
|
|
|
// SignTxWithPassphrase requests the wallet to sign the given transaction, with the
|
|
// given passphrase as extra authentication information.
|
|
//
|
|
// It looks up the account specified either solely via its address contained within,
|
|
// or optionally with the aid of any location metadata from the embedded URL field.
|
|
func (w *Wallet) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
|
|
if !w.session.verified {
|
|
if err := w.Open(passphrase); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return w.SignTx(account, tx, chainID)
|
|
}
|
|
|
|
// findAccountPath returns the derivation path for the provided account.
|
|
// It first checks for the address in the list of pinned accounts, and if it is
|
|
// not found, attempts to parse the derivation path from the account's URL.
|
|
func (w *Wallet) findAccountPath(account accounts.Account) (accounts.DerivationPath, error) {
|
|
pairing := w.Hub.pairing(w)
|
|
if path, ok := pairing.Accounts[account.Address]; ok {
|
|
return path, nil
|
|
}
|
|
|
|
// Look for the path in the URL
|
|
if account.URL.Scheme != w.Hub.scheme {
|
|
return nil, fmt.Errorf("scheme %s does not match wallet scheme %s", account.URL.Scheme, w.Hub.scheme)
|
|
}
|
|
|
|
url, path, found := strings.Cut(account.URL.Path, "/")
|
|
if !found {
|
|
return nil, fmt.Errorf("invalid URL format: %s", account.URL)
|
|
}
|
|
|
|
if url != fmt.Sprintf("%x", w.PublicKey[1:3]) {
|
|
return nil, fmt.Errorf("URL %s is not for this wallet", account.URL)
|
|
}
|
|
|
|
return accounts.ParseDerivationPath(path)
|
|
}
|
|
|
|
// Session represents a secured communication session with the wallet.
|
|
type Session struct {
|
|
Wallet *Wallet // A handle to the wallet that opened the session
|
|
Channel *SecureChannelSession // A secure channel for encrypted messages
|
|
verified bool // Whether the pin has been verified in this session.
|
|
}
|
|
|
|
// pair establishes a new pairing over this channel, using the provided secret.
|
|
func (s *Session) pair(secret []byte) (smartcardPairing, error) {
|
|
err := s.Channel.Pair(secret)
|
|
if err != nil {
|
|
return smartcardPairing{}, err
|
|
}
|
|
|
|
return smartcardPairing{
|
|
PublicKey: s.Wallet.PublicKey,
|
|
PairingIndex: s.Channel.PairingIndex,
|
|
PairingKey: s.Channel.PairingKey,
|
|
Accounts: make(map[common.Address]accounts.DerivationPath),
|
|
}, nil
|
|
}
|
|
|
|
// unpair deletes an existing pairing.
|
|
func (s *Session) unpair() error {
|
|
if !s.verified {
|
|
return errors.New("unpair requires that the PIN be verified")
|
|
}
|
|
|
|
return s.Channel.Unpair()
|
|
}
|
|
|
|
// verifyPin unlocks a wallet with the provided pin.
|
|
func (s *Session) verifyPin(pin []byte) error {
|
|
if _, err := s.Channel.transmitEncrypted(claSCWallet, insVerifyPin, 0, 0, pin); err != nil {
|
|
return err
|
|
}
|
|
|
|
s.verified = true
|
|
|
|
return nil
|
|
}
|
|
|
|
// unblockPin unblocks a wallet with the provided puk and resets the pin to the
|
|
// new one specified.
|
|
func (s *Session) unblockPin(pukpin []byte) error {
|
|
if _, err := s.Channel.transmitEncrypted(claSCWallet, insUnblockPin, 0, 0, pukpin); err != nil {
|
|
return err
|
|
}
|
|
|
|
s.verified = true
|
|
|
|
return nil
|
|
}
|
|
|
|
// release releases resources associated with the channel.
|
|
func (s *Session) release() error {
|
|
return s.Wallet.card.Disconnect(pcsc.LeaveCard)
|
|
}
|
|
|
|
// paired returns true if a valid pairing exists.
|
|
func (s *Session) paired() bool {
|
|
return s.Channel.PairingKey != nil
|
|
}
|
|
|
|
// authenticate uses an existing pairing to establish a secure channel.
|
|
func (s *Session) authenticate(pairing smartcardPairing) error {
|
|
if !bytes.Equal(s.Wallet.PublicKey, pairing.PublicKey) {
|
|
return fmt.Errorf("cannot pair using another wallet's pairing; %x != %x", s.Wallet.PublicKey, pairing.PublicKey)
|
|
}
|
|
|
|
s.Channel.PairingKey = pairing.PairingKey
|
|
s.Channel.PairingIndex = pairing.PairingIndex
|
|
|
|
return s.Channel.Open()
|
|
}
|
|
|
|
// walletStatus describes a smartcard wallet's status information.
|
|
type walletStatus struct {
|
|
PinRetryCount int // Number of remaining PIN retries
|
|
PukRetryCount int // Number of remaining PUK retries
|
|
Initialized bool // Whether the card has been initialized with a private key
|
|
}
|
|
|
|
// walletStatus fetches the wallet's status from the card.
|
|
func (s *Session) walletStatus() (*walletStatus, error) {
|
|
response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1WalletStatus, 0, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
status := new(walletStatus)
|
|
if _, err := asn1.UnmarshalWithParams(response.Data, status, "tag:3"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return status, nil
|
|
}
|
|
|
|
// derivationPath fetches the wallet's current derivation path from the card.
|
|
//
|
|
//lint:ignore U1000 needs to be added to the console interface
|
|
func (s *Session) derivationPath() (accounts.DerivationPath, error) {
|
|
response, err := s.Channel.transmitEncrypted(claSCWallet, insStatus, statusP1Path, 0, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
buf := bytes.NewReader(response.Data)
|
|
path := make(accounts.DerivationPath, len(response.Data)/4)
|
|
|
|
return path, binary.Read(buf, binary.BigEndian, &path)
|
|
}
|
|
|
|
// initializeData contains data needed to initialize the smartcard wallet.
|
|
type initializeData struct {
|
|
PublicKey []byte `asn1:"tag:0"`
|
|
PrivateKey []byte `asn1:"tag:1"`
|
|
ChainCode []byte `asn1:"tag:2"`
|
|
}
|
|
|
|
// initialize initializes the card with new key data.
|
|
func (s *Session) initialize(seed []byte) error {
|
|
// Check that the wallet isn't currently initialized,
|
|
// otherwise the key would be overwritten.
|
|
status, err := s.Wallet.Status()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if status == "Online" {
|
|
return errors.New("card is already initialized, cowardly refusing to proceed")
|
|
}
|
|
|
|
s.Wallet.lock.Lock()
|
|
defer s.Wallet.lock.Unlock()
|
|
|
|
// HMAC the seed to produce the private key and chain code
|
|
mac := hmac.New(sha512.New, []byte("Bitcoin seed"))
|
|
mac.Write(seed)
|
|
seed = mac.Sum(nil)
|
|
|
|
key, err := crypto.ToECDSA(seed[:32])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
id := initializeData{}
|
|
id.PublicKey = crypto.FromECDSAPub(&key.PublicKey)
|
|
id.PrivateKey = seed[:32]
|
|
id.ChainCode = seed[32:]
|
|
|
|
data, err := asn1.Marshal(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Nasty hack to force the top-level struct tag to be context-specific
|
|
data[0] = 0xA1
|
|
|
|
_, err = s.Channel.transmitEncrypted(claSCWallet, insLoadKey, 0x02, 0, data)
|
|
|
|
return err
|
|
}
|
|
|
|
// derive derives a new HD key path on the card.
|
|
func (s *Session) derive(path accounts.DerivationPath) (accounts.Account, error) {
|
|
startingPoint, path, err := derivationpath.Decode(path.String())
|
|
if err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
var p1 uint8
|
|
|
|
switch startingPoint {
|
|
case derivationpath.StartingPointMaster:
|
|
p1 = P1DeriveKeyFromMaster
|
|
case derivationpath.StartingPointParent:
|
|
p1 = P1DeriveKeyFromParent
|
|
case derivationpath.StartingPointCurrent:
|
|
p1 = P1DeriveKeyFromCurrent
|
|
default:
|
|
return accounts.Account{}, fmt.Errorf("invalid startingPoint %d", startingPoint)
|
|
}
|
|
|
|
data := new(bytes.Buffer)
|
|
for _, segment := range path {
|
|
if err := binary.Write(data, binary.BigEndian, segment); err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
}
|
|
|
|
_, err = s.Channel.transmitEncrypted(claSCWallet, insDeriveKey, p1, 0, data.Bytes())
|
|
if err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, 0, 0, DerivationSignatureHash[:])
|
|
if err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
sigdata := new(signatureData)
|
|
if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
|
|
sig := make([]byte, 65)
|
|
copy(sig[32-len(rbytes):32], rbytes)
|
|
copy(sig[64-len(sbytes):64], sbytes)
|
|
|
|
if err := confirmPublicKey(sig, sigdata.PublicKey); err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
pub, err := crypto.UnmarshalPubkey(sigdata.PublicKey)
|
|
if err != nil {
|
|
return accounts.Account{}, err
|
|
}
|
|
|
|
return s.Wallet.makeAccount(crypto.PubkeyToAddress(*pub), path), nil
|
|
}
|
|
|
|
// keyExport contains information on an exported keypair.
|
|
//
|
|
//lint:ignore U1000 needs to be added to the console interface
|
|
type keyExport struct {
|
|
PublicKey []byte `asn1:"tag:0"`
|
|
PrivateKey []byte `asn1:"tag:1,optional"`
|
|
}
|
|
|
|
// publicKey returns the public key for the current derivation path.
|
|
//
|
|
//lint:ignore U1000 needs to be added to the console interface
|
|
func (s *Session) publicKey() ([]byte, error) {
|
|
response, err := s.Channel.transmitEncrypted(claSCWallet, insExportKey, exportP1Any, exportP2Pubkey, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
keys := new(keyExport)
|
|
if _, err := asn1.UnmarshalWithParams(response.Data, keys, "tag:1"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return keys.PublicKey, nil
|
|
}
|
|
|
|
// signatureData contains information on a signature - the signature itself and
|
|
// the corresponding public key.
|
|
type signatureData struct {
|
|
PublicKey []byte `asn1:"tag:0"`
|
|
Signature struct {
|
|
R *big.Int
|
|
S *big.Int
|
|
}
|
|
}
|
|
|
|
// sign asks the card to sign a message, and returns a valid signature after
|
|
// recovering the v value.
|
|
func (s *Session) sign(path accounts.DerivationPath, hash []byte) ([]byte, error) {
|
|
startTime := time.Now()
|
|
|
|
_, err := s.derive(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
deriveTime := time.Now()
|
|
|
|
response, err := s.Channel.transmitEncrypted(claSCWallet, insSign, signP1PrecomputedHash, signP2OnlyBlock, hash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
sigdata := new(signatureData)
|
|
if _, err := asn1.UnmarshalWithParams(response.Data, sigdata, "tag:0"); err != nil {
|
|
return nil, err
|
|
}
|
|
// Serialize the signature
|
|
rbytes, sbytes := sigdata.Signature.R.Bytes(), sigdata.Signature.S.Bytes()
|
|
sig := make([]byte, 65)
|
|
copy(sig[32-len(rbytes):32], rbytes)
|
|
copy(sig[64-len(sbytes):64], sbytes)
|
|
|
|
// Recover the V value.
|
|
sig, err = makeRecoverableSignature(hash, sig, sigdata.PublicKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
log.Debug("Signed using smartcard", "deriveTime", deriveTime.Sub(startTime), "signingTime", time.Since(deriveTime))
|
|
|
|
return sig, nil
|
|
}
|
|
|
|
// confirmPublicKey confirms that the given signature belongs to the specified key.
|
|
func confirmPublicKey(sig, pubkey []byte) error {
|
|
_, err := makeRecoverableSignature(DerivationSignatureHash[:], sig, pubkey)
|
|
return err
|
|
}
|
|
|
|
// makeRecoverableSignature uses a signature and an expected public key to
|
|
// recover the v value and produce a recoverable signature.
|
|
func makeRecoverableSignature(hash, sig, expectedPubkey []byte) ([]byte, error) {
|
|
var libraryError error
|
|
|
|
for v := 0; v < 2; v++ {
|
|
sig[64] = byte(v)
|
|
if pubkey, err := crypto.Ecrecover(hash, sig); err == nil {
|
|
if bytes.Equal(pubkey, expectedPubkey) {
|
|
return sig, nil
|
|
}
|
|
} else {
|
|
libraryError = err
|
|
}
|
|
}
|
|
|
|
if libraryError != nil {
|
|
return nil, libraryError
|
|
}
|
|
|
|
return nil, ErrPubkeyMismatch
|
|
}
|