erigon-pulse/cmd/clef
Igor Mandrigin 8c3d19fd4c
geth 1.9.13 (#469)
* core: initial version of state snapshots

* core/state: lazy sorting, snapshot invalidation

* core/state/snapshot: extract and split cap method, cover corners

* snapshot: iteration and buffering optimizations

* core/state/snapshot: unlink snapshots from blocks, quad->linear cleanup

* 123

* core/rawdb, core/state/snapshot: runtime snapshot generation

* core/state/snapshot: fix difflayer origin-initalization after flatten

* add "to merge"

* core/state/snapshot: implement snapshot layer iteration

* core/state/snapshot: node behavioural difference on bloom content

* core: journal the snapshot inside leveldb, not a flat file

* core/state/snapshot: bloom, metrics and prefetcher fixes

* core/state/snapshot: move iterator out into its own files

* core/state/snapshot: implement iterator priority for fast direct data lookup

* core/state/snapshot: full featured account iteration

* core/state/snapshot: faster account iteration, CLI integration

* core: fix broken tests due to API changes + linter

* core/state: fix an account resurrection issue

* core/tests: test for destroy+recreate contract with storage

* squashme

* core/state/snapshot, tests: sync snap gen + snaps in consensus tests

* core/state: extend snapshotter to handle account resurrections

* core/state: fix account root hash update point

* core/state: fix resurrection state clearing and access

* core/state/snapshot: handle deleted accounts in fast iterator

* core: more blockchain tests

* core/state/snapshot: fix various iteration issues due to destruct set

* core: fix two snapshot iterator flaws, decollide snap storage prefix

* core/state/snapshot/iterator: fix two disk iterator flaws

* core/rawdb: change SnapshotStoragePrefix to avoid prefix collision with preimagePrefix

* params: begin v1.9.13 release cycle

* cmd/checkpoint-admin: add some documentation (#20697)

* go.mod: update duktape to fix sprintf warnings (#20777)

This revision of go-duktype fixes the following warning

```
duk_logging.c: In function ‘duk__logger_prototype_log_shared’:
duk_logging.c:184:64: warning: ‘Z’ directive writing 1 byte into a region of size between 0 and 9 [-Wformat-overflow=]
  184 |  sprintf((char *) date_buf, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
      |                                                                ^
In file included from /usr/include/stdio.h:867,
                 from duk_logging.c:5:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:36:10: note: ‘__builtin___sprintf_chk’ output between 25 and 85 bytes into a destination of size 32
   36 |   return __builtin___sprintf_chk (__s, __USE_FORTIFY_LEVEL - 1,
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   37 |       __bos (__s), __fmt, __va_arg_pack ());
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

* core/rawdb: fix freezer table test error check

Fixes: Condition is always 'false' because 'err' is always 'nil'

* core/rawdb: improve table database (#20703)

This PR fixes issues in TableDatabase.

TableDatabase is a wrapper of underlying ethdb.Database with an additional prefix.
The prefix is applied to all entries it maintains. However when we try to retrieve entries
from it we don't handle the key properly. In theory the prefix should be truncated and
only user key is returned. But we don't do it in some cases, e.g. the iterator and batch
replayer created from it. So this PR is the fix to these issues.

* eth: when triggering a sync, check the head header TD, not block

* internal/web3ext: fix clique console apis to work on missing arguments

* rpc: dont log an error if user configures --rpcapi=rpc... (#20776)

This just prevents a false negative ERROR warning when, for some unknown
reason, a user attempts to turn on the module rpc even though it's already going
to be on.

* node, cmd/clef: report actual port used for http rpc (#20789)

* internal/ethapi: don't set sender-balance to maxuint, fixes #16999 (#20783)

Prior to this change, eth_call changed the balance of the sender account in the
EVM environment to 2^256 wei to cover the gas cost of the call execution.
We've had this behavior for a long time even though it's super confusing.

This commit sets the default call gasprice to zero instead of updating the balance,
which is better because it makes eth_call semantics less surprising. Removing
the built-in balance assignment also makes balance overrides work as expected.

* metrics: disable CPU stats (gosigar) on iOS

* cmd/devp2p: tweak DNS TTLs (#20801)

* cmd/devp2p: tweak DNS TTLs

* cmd/devp2p: bump treeNodeTTL to four weeks

* cmd/devp2p: lower route53 change limit again (#20819)

* cmd/devp2p: be very correct about route53 change splitting (#20820)

Turns out the way RDATA limits work is documented after all,
I just didn't search right. The trick to make it work is to
count UPSERTs twice.

This also adds an additional check to ensure TTL changes are
applied on existing records.

* graphql, node, rpc: fix typos in comments (#20824)

* eth: improve shutdown synchronization (#20695)

* eth: improve shutdown synchronization

Most goroutines started by eth.Ethereum didn't have any shutdown sync at
all, which lead to weird error messages when quitting the client.

This change improves the clean shutdown path by stopping all internal
components in dependency order and waiting for them to actually be
stopped before shutdown is considered done. In particular, we now stop
everything related to peers before stopping 'resident' parts such as
core.BlockChain.

* eth: rewrite sync controller

* eth: remove sync start debug message

* eth: notify chainSyncer about new peers after handshake

* eth: move downloader.Cancel call into chainSyncer

* eth: make post-sync block broadcast synchronous

* eth: add comments

* core: change blockchain stop message

* eth: change closeBloomHandler channel type

* eth/filters: fix typo on unindexedLogs function's comment (#20827)

* core: bump txpool tx max size to 128KB

* snapshotter/tests: verify snapdb post-state against trie (#20812)

* core/state/snapshot: basic trie-to-hash implementation

* tests: validate snapshot after test

* core/state/snapshot: fix review concerns

* cmd, consensus: add option to disable mmap for DAG caches/datasets (#20484)

* cmd, consensus: add option to disable mmap for DAG caches/datasets

* consensus: add benchmarks for mmap with/with lock

* cmd/clef: add newaccount command (#20782)

* cmd/clef: add newaccount command

* cmd/clef: document clef_New, update API versioning

* Update cmd/clef/intapi_changelog.md

Co-Authored-By: ligi <ligi@ligi.de>

* Update signer/core/uiapi.go

Co-Authored-By: ligi <ligi@ligi.de>

Co-authored-by: ligi <ligi@ligi.de>

* eth: add debug_accountRange API (#19645)

This new API allows reading accounts and their content by address range.

Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: Felix Lange <fjl@twurst.com>

* travis: allow cocoapods deploy to fail (#20833)

* metrics: improve TestTimerFunc (#20818)

The test failed due to what appears to be fluctuations in time.Sleep, which is
not the actual method under test. This change modifies it so we compare the
metered Max to the actual time instead of the desired time.

* README: update private network genesis spec with istanbul (#20841)

* add istanbul and muirGlacier to genesis states in README

* remove muirGlacier, relocate istanbul

* cmd/evm: Rework execution stats (#20792)

- Dump stats also for --bench flag.
- From memory stats only show number and size of allocations. This is what `test -bench` shows. I doubt others like number of GC runs are any useful, but can be added if requested.
- Now the mem stats are for single execution in case of --bench.

* cmd/devp2p, cmd/wnode, whisper: add missing calls to Timer.Stop (#20843)

* p2p/server: add UDP port mapping goroutine to wait group (#20846)

* accounts/abi faster unpacking of int256 (#20850)

* p2p/discv5: add missing Timer.Stop calls (#20853)

* miner/worker: add missing timer.Stop call (#20857)

* cmd/geth: fix bad genesis test (#20860)

* eth/filters: add missing Ticker.Stop call (#20862)

* eth/fetcher: add missing timer.Stop calls (#20861)

* event: add missing timer.Stop call in TestFeed (#20868)

* metrics: add missing calls to Ticker.Stop in tests (#20866)

* ethstats: add missing Ticker.Stop call (#20867)

* p2p/discv5, p2p/testing: add missing Timer.Stop calls in tests (#20869)

* core: add missing Timer.Stop call in TestLogReorgs (#20870)

* rpc: add missing timer.Stop calls in websocket tests (#20863)

* crypto/ecies: improve concatKDF (#20836)

This removes a bunch of weird code around the counter overflow check in
concatKDF and makes it actually work for different hash output sizes.

The overflow check worked as follows: concatKDF applies the hash function N
times, where N is roundup(kdLen, hashsize) / hashsize. N should not
overflow 32 bits because that would lead to a repetition in the KDF output.

A couple issues with the overflow check:

- It used the hash.BlockSize, which is wrong because the
  block size is about the input of the hash function. Luckily, all standard
  hash functions have a block size that's greater than the output size, so
  concatKDF didn't crash, it just generated too much key material.
- The check used big.Int to compare against 2^32-1.
- The calculation could still overflow before reaching the check.

The new code in concatKDF doesn't check for overflow. Instead, there is a
new check on ECIESParams which ensures that params.KeyLen is < 512. This
removes any possibility of overflow.

There are a couple of miscellaneous improvements bundled in with this
change:

- The key buffer is pre-allocated instead of appending the hash output
  to an initially empty slice.
- The code that uses concatKDF to derive keys is now shared between Encrypt
  and Decrypt.
- There was a redundant invocation of IsOnCurve in Decrypt. This is now removed
  because elliptic.Unmarshal already checks whether the input is a valid curve
  point since Go 1.5.

Co-authored-by: Felix Lange <fjl@twurst.com>

* rpc: metrics for JSON-RPC method calls (#20847)

This adds a couple of metrics for tracking the timing
and frequency of method calls:

- rpc/requests gauge counts all requests
- rpc/success gauge counts requests which return err == nil
- rpc/failure gauge counts requests which return err != nil
- rpc/duration/all timer tracks timing of all requests
- rpc/duration/<method>/<success/failure> tracks per-method timing

* mobile: use bind.NewKeyedTransactor instead of duplicating (#20888)

It's better to reuse the existing code to create a keyed transactor
than to rewrite the logic again.

* internal/ethapi: add CallArgs.ToMessage method (#20854)

ToMessage is used to convert between ethapi.CallArgs and types.Message.
It reduces the length of the DoCall method by about half by abstracting out
the conversion between the CallArgs and the Message. This should improve the
code's maintainability and reusability.

* eth, les: fix flaky tests (#20897)

* les: fix flaky test

* eth: fix flaky test

* cmd/geth: enable metrics for geth import command (#20738)

* cmd/geth: enable metrics for geth import command

* cmd/geth: enable metrics-flags for import command

* core/vm: use a callcontext struct (#20761)

* core/vm: use a callcontext struct

* core/vm: fix tests

* core/vm/runtime: benchmark

* core/vm: make intpool push inlineable, unexpose callcontext

* docs/audits: add discv5 protocol audits from LA and C53 (#20898)

* .github: change gitter reference to discord link in issue template (#20896)

* couple of fixes to docs in clef (#20900)

* p2p/discover: add initial discovery v5 implementation (#20750)This adds an implementation of the current discovery v5 spec.There is full integration with cmd/devp2p and enode.Iterator in thisversion. In theory we could enable the new protocol as a replacement ofdiscovery v4 at any time. In practice, there will likely be a few morechanges to the spec and implementation before this can happen.

* build: upgrade to golangci-lint 1.24.0 (#20901)

* accounts/scwallet: remove unnecessary uses of fmt.Sprintf

* cmd/puppeth: remove unnecessary uses of fmt.Sprintf

* p2p/discv5: remove unnecessary use of fmt.Sprintf

* whisper/mailserver: remove unnecessary uses of fmt.Sprintf

* core: goimports -w tx_pool_test.go

* eth/downloader: goimports -w downloader_test.go

* build: upgrade to golangci-lint 1.24.0

* accounts/abi/bind: Refactored topics  (#20851)

* accounts/abi/bind: refactored topics

* accounts/abi/bind: use store function to remove code duplication

* accounts/abi/bind: removed unused type defs

* accounts/abi/bind: error on tuples in topics

* Cosmetic changes to restart travis build

Co-authored-by: Guillaume Ballet <gballet@gmail.com>

* node: allow websocket and HTTP on the same port (#20810)

This change makes it possible to run geth with JSON-RPC over HTTP and
WebSocket on the same TCP port. The default port for WebSocket
is still 8546.

    geth --rpc --rpcport 8545 --ws --wsport 8545

This also removes a lot of deprecated API surface from package rpc.
The rpc package is now purely about serving JSON-RPC and no longer
provides a way to start an HTTP server.

* crypto: improve error messages in LoadECDSA (#20718)

This improves error messages when the file is too short or too long.
Also rewrite the test for SaveECDSA because LoadECDSA has its own
test now.

Co-authored-by: Felix Lange <fjl@twurst.com>

* changed date of rpcstack.go since new file (#20904)

* accounts/abi/bind: fixed erroneous filtering of negative ints (#20865)

* accounts/abi/bind: fixed erroneous packing of negative ints

* accounts/abi/bind: added test cases for negative ints in topics

* accounts/abi/bind: fixed genIntType for go 1.12

* accounts/abi: minor  nitpick

* cmd: deprecate --testnet, use named networks instead (#20852)

* cmd/utils: make goerli the default testnet

* cmd/geth: explicitly rename testnet to ropsten

* core: explicitly rename testnet to ropsten

* params: explicitly rename testnet to ropsten

* cmd: explicitly rename testnet to ropsten

* miner: explicitly rename testnet to ropsten

* mobile: allow for returning the goerli spec

* tests: explicitly rename testnet to ropsten

* docs: update readme to reflect changes to the default testnet

* mobile: allow for configuring goerli and rinkeby nodes

* cmd/geth: revert --testnet back to ropsten and mark as legacy

* cmd/util: mark --testnet flag as deprecated

* docs: update readme to properly reflect the 3 testnets

* cmd/utils: add an explicit deprecation warning on startup

* cmd/utils: swap goerli and ropsten in usage

* cmd/geth: swap goerli and ropsten in usage

* cmd/geth: if running a known preset, log it for convenience

* docs: improve readme on usage of ropsten's testnet datadir

* cmd/utils: check if legacy `testnet` datadir exists for ropsten

* cmd/geth: check for legacy testnet path in console command

* cmd/geth: use switch statement for complex conditions in main

* cmd/geth: move known preset log statement to the very top

* cmd/utils: create new ropsten configurations in the ropsten datadir

* cmd/utils: makedatadir should check for existing testnet dir

* cmd/geth: add legacy testnet flag to the copy db command

* cmd/geth: add legacy testnet flag to the inspect command

* les, les/lespay/client: add service value statistics and API (#20837)

This PR adds service value measurement statistics to the light client. It
also adds a private API that makes these statistics accessible. A follow-up
PR will add the new server pool which uses these statistics to select
servers with good performance.

This document describes the function of the new components:
https://gist.github.com/zsfelfoldi/3c7ace895234b7b345ab4f71dab102d4

Co-authored-by: rjl493456442 <garyrong0905@gmail.com>
Co-authored-by: rjl493456442 <garyrong0905@gmail.com>

* README: update min go version to 1.13 (#20911)

* travis, appveyor, build, Dockerfile: bump Go to 1.14.2 (#20913)

* travis, appveyor, build, Dockerfile: bump Go to 1.14.2

* travis, appveyor: force GO111MODULE=on for every build

* core/rawdb: fix data race between Retrieve and Close (#20919)

* core/rawdb: fixed data race between retrieve and close

closes https://github.com/ethereum/go-ethereum/issues/20420

* core/rawdb: use non-atomic load while holding mutex

* all: simplify and fix database iteration with prefix/start (#20808)

* core/state/snapshot: start fixing disk iterator seek

* ethdb, rawdb, leveldb, memorydb: implement iterators with prefix and start

* les, core/state/snapshot: iterator fixes

* all: remove two iterator methods

* all: rename Iteratee.NewIteratorWith -> NewIterator

* ethdb: fix review concerns

* params: update CHTs for the 1.9.13 release

* params: release Geth v1.9.13

* added some missing files

* post-rebase fixups

Co-authored-by: Péter Szilágyi <peterke@gmail.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
Co-authored-by: gary rong <garyrong0905@gmail.com>
Co-authored-by: Alex Willmer <alex@moreati.org.uk>
Co-authored-by: meowsbits <45600330+meowsbits@users.noreply.github.com>
Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: rene <41963722+renaynay@users.noreply.github.com>
Co-authored-by: Ha ĐANG <dvietha@gmail.com>
Co-authored-by: Hanjiang Yu <42531996+de1acr0ix@users.noreply.github.com>
Co-authored-by: ligi <ligi@ligi.de>
Co-authored-by: Wenbiao Zheng <delweng@gmail.com>
Co-authored-by: Adam Schmideg <adamschmideg@users.noreply.github.com>
Co-authored-by: Jeff Wentworth <jeff@curvegrid.com>
Co-authored-by: Paweł Bylica <chfast@gmail.com>
Co-authored-by: ucwong <ucwong@126.com>
Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de>
Co-authored-by: Luke Champine <luke.champine@gmail.com>
Co-authored-by: Boqin Qin <Bobbqqin@gmail.com>
Co-authored-by: William Morriss <wjmelements@gmail.com>
Co-authored-by: Guillaume Ballet <gballet@gmail.com>
Co-authored-by: Raw Pong Ghmoa <58883403+q9f@users.noreply.github.com>
Co-authored-by: Felföldi Zsolt <zsfelfoldi@gmail.com>
2020-04-19 18:31:47 +01:00
..
docs geth 1.9.13 (#469) 2020-04-19 18:31:47 +01:00
tests all: update author list and licenses 2019-07-22 12:17:27 +03:00
datatypes.md cmd/clef, signer: refresh tutorial, fix noticed issues (#19774) 2019-07-02 14:01:47 +03:00
extapi_changelog.md cmd/clef, signer: refresh tutorial, fix noticed issues (#19774) 2019-07-02 14:01:47 +03:00
intapi_changelog.md geth 1.9.13 (#469) 2020-04-19 18:31:47 +01:00
main.go geth 1.9.13 (#469) 2020-04-19 18:31:47 +01:00
pythonsigner.py cmd/clef, signer: refresh tutorial, fix noticed issues (#19774) 2019-07-02 14:01:47 +03:00
README.md cmd/clef: spelling correction (#19973) 2019-08-19 13:31:45 +03:00
rules.md cmd, crypto, eth, internals: fix Typos (#19868) 2019-07-22 10:34:33 +03:00
sign_flow.png [ImgBot] optimizes images (#17741) 2018-09-26 10:39:39 +02:00
tutorial.md docs: correct clef typo (#20705) 2020-03-16 16:40:19 +03:00

Clef

Clef can be used to sign transactions and data and is meant as a(n eventual) replacement for Geth's account management. This allows DApps to not depend on Geth's account management. When a DApp wants to sign data (or a transaction), it can send the content to Clef, which will then provide the user with context and asks for permission to sign the content. If the users grants the signing request, Clef will send the signature back to the DApp.

This setup allows a DApp to connect to a remote Ethereum node and send transactions that are locally signed. This can help in situations when a DApp is connected to an untrusted remote Ethereum node, because a local one is not available, not synchronised with the chain, or is a node that has no built-in (or limited) account management.

Clef can run as a daemon on the same machine, off a usb-stick like USB armory, or even a separate VM in a QubesOS type setup.

Check out the

  • CLI tutorial for some concrete examples on how Clef works.
  • Setup docs for infos on how to configure Clef on QubesOS or USB Armory.
  • Data types for details on the communication messages between Clef and an external UI.

Command line flags

Clef accepts the following command line options:

COMMANDS:
   init    Initialize the signer, generate secret storage
   attest  Attest that a js-file is to be used
   setpw   Store a credential for a keystore file
   delpw   Remove a credential for a keystore file
   gendoc  Generate documentation about json-rpc format
   help    Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --loglevel value        log level to emit to the screen (default: 4)
   --keystore value        Directory for the keystore (default: "$HOME/.ethereum/keystore")
   --configdir value       Directory for Clef configuration (default: "$HOME/.clef")
   --chainid value         Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli) (default: 1)
   --lightkdf              Reduce key-derivation RAM & CPU usage at some expense of KDF strength
   --nousb                 Disables monitoring for and managing USB hardware wallets
   --pcscdpath value       Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm")
   --rpcaddr value         HTTP-RPC server listening interface (default: "localhost")
   --rpcvhosts value       Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
   --ipcdisable            Disable the IPC-RPC server
   --ipcpath               Filename for IPC socket/pipe within the datadir (explicit paths escape it)
   --rpc                   Enable the HTTP-RPC server
   --rpcport value         HTTP-RPC server listening port (default: 8550)
   --signersecret value    A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash
   --4bytedb-custom value  File used for writing new 4byte-identifiers submitted via API (default: "./4byte-custom.json")
   --auditlog value        File used to emit audit logs. Set to "" to disable (default: "audit.log")
   --rules value           Path to the rule file to auto-authorize requests with
   --stdio-ui              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.
   --stdio-ui-test         Mechanism to test interface between Clef and UI. Requires 'stdio-ui'.
   --advanced              If enabled, issues warnings instead of rejections for suspicious requests. Default off
   --help, -h              show help
   --version, -v           print the version

Example:

$ clef -keystore /my/keystore -chainid 4

Security model

The security model of Clef is as follows:

  • One critical component (the Clef binary / daemon) is responsible for handling cryptographic operations: signing, private keys, encryption/decryption of keystore files.
  • Clef has a well-defined 'external' API.
  • The 'external' API is considered UNTRUSTED.
  • Clef also communicates with whatever process that invoked the binary, via stdin/stdout.
    • This channel is considered 'trusted'. Over this channel, approvals and passwords are communicated.

The general flow for signing a transaction using e.g. Geth is as follows: image

In this case, geth would be started with --signer http://localhost:8550 and would relay requests to eth.sendTransaction.

TODOs

Some snags and todos

  • Clef should take a startup param "--no-change", for UIs that do not contain the capability to perform changes to things, only approve/deny. Such a UI should be able to start the signer in a more secure mode by telling it that it only wants approve/deny capabilities.

  • It would be nice if Clef could collect new 4byte-id:s/method selectors, and have a secondary database for those (4byte_custom.json). Users could then (optionally) submit their collections for inclusion upstream.

  • It should be possible to configure Clef to check if an account is indeed known to it, before passing on to the UI. The reason it currently does not, is that it would make it possible to enumerate accounts if it immediately returned "unknown account" (side channel attack).

  • It should be possible to configure Clef to auto-allow listing (certain) accounts, instead of asking every time.

  • Done Upon startup, Clef should spit out some info to the caller (particularly important when executed in stdio-ui-mode), invoking methods with the following info:

    • Version info about the signer
    • Address of API (HTTP/IPC)
    • List of known accounts
  • Have a default timeout on signing operations, so that if the user has not answered within e.g. 60 seconds, the request is rejected.

  • account_signRawTransaction

  • account_bulkSignTransactions([] transactions) should

    • only exist if enabled via config/flag
    • only allow non-data-sending transactions
    • all txs must use the same from-account
    • let the user confirm, showing
      • the total amount
      • the number of unique recipients
  • Geth todos

    • The signer should pass the Origin header as call-info to the UI. As of right now, the way that info about the request is put together is a bit of a hack into the HTTP server. This could probably be greatly improved.
    • Relay: Geth should be started in geth --signer localhost:8550.
    • Currently, the Geth APIs use common.Address in the arguments to transaction submission (e.g to field). This type is 20 bytes, and is incapable of carrying checksum information. The signer uses common.MixedcaseAddress, which retains the original input.
    • The Geth API should switch to use the same type, and relay to-account verbatim to the external API.
  • Storage

    • An encrypted key-value storage should be implemented.
    • See rules.md for more info about this.
  • Another potential thing to introduce is pairing.

    • To prevent spurious requests which users just accept, implement a way to "pair" the caller with the signer (external API).
    • Thus Geth/cpp would cryptographically handshake and afterwards the caller would be allowed to make signing requests.
    • This feature would make the addition of rules less dangerous.
  • Wallets / accounts. Add API methods for wallets.

Communication

External API

Clef listens to HTTP requests on rpcaddr:rpcport (or to IPC on ipcpath), with the same JSON-RPC standard as Geth. The messages are expected to be JSON-RPC 2.0 standard.

Some of these call can require user interaction. Clients must be aware that responses may be delayed significantly or may never be received if a users decides to ignore the confirmation request.

The External API is untrusted: it does not accept credentials over this API, nor does it expect that requests have any authority.

Internal UI API

Clef has one native console-based UI, for operation without any standalone tools. However, there is also an API to communicate with an external UI. To enable that UI, the signer needs to be executed with the --stdio-ui option, which allocates stdin / stdout for the UI API.

An example (insecure) proof-of-concept of has been implemented in pythonsigner.py.

The model is as follows:

  • The user starts the UI app (pythonsigner.py).
  • The UI app starts clef with --stdio-ui, and listens to the process output for confirmation-requests.
  • clef opens the external HTTP API.
  • When the signer receives requests, it sends a JSON-RPC request via stdout.
  • The UI app prompts the user accordingly, and responds to clef.
  • clef signs (or not), and responds to the original request.

External API

See the external API changelog for information about changes to this API.

Encoding

  • number: positive integers that are hex encoded
  • data: hex encoded data
  • string: ASCII string

All hex encoded values must be prefixed with 0x.

Methods

account_new

Create new password protected account

The signer will generate a new private key, encrypts it according to web3 keystore spec and stores it in the keystore directory. The client is responsible for creating a backup of the keystore. If the keystore is lost there is no method of retrieving lost accounts.

Arguments

None

Result

  • address [string]: account address that is derived from the generated key
  • url [string]: location of the keyfile

Sample call

{
  "id": 0,
  "jsonrpc": "2.0",
  "method": "account_new",
  "params": []
}

Response

{
  "id": 0,
  "jsonrpc": "2.0",
  "result": {
    "address": "0xbea9183f8f4f03d427f6bcea17388bdff1cab133",
    "url": "keystore:///my/keystore/UTC--2017-08-24T08-40-15.419655028Z--bea9183f8f4f03d427f6bcea17388bdff1cab133"
  }
}

account_list

List available accounts

List all accounts that this signer currently manages

Arguments

None

Result

  • array with account records:
    • account.address [string]: account address that is derived from the generated key
    • account.type [string]: type of the
    • account.url [string]: location of the account

Sample call

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "account_list"
}

Response

{
  "id": 1,
  "jsonrpc": "2.0",
  "result": [
    {
      "address": "0xafb2f771f58513609765698f65d3f2f0224a956f",
      "type": "account",
      "url": "keystore:///tmp/keystore/UTC--2017-08-24T07-26-47.162109726Z--afb2f771f58513609765698f65d3f2f0224a956f"
    },
    {
      "address": "0xbea9183f8f4f03d427f6bcea17388bdff1cab133",
      "type": "account",
      "url": "keystore:///tmp/keystore/UTC--2017-08-24T08-40-15.419655028Z--bea9183f8f4f03d427f6bcea17388bdff1cab133"
    }
  ]
}

account_signTransaction

Sign transactions

Signs a transactions and responds with the signed transaction in RLP encoded form.

Arguments

  1. transaction object:
    • from [address]: account to send the transaction from
    • to [address]: receiver account. If omitted or 0x, will cause contract creation.
    • gas [number]: maximum amount of gas to burn
    • gasPrice [number]: gas price
    • value [number:optional]: amount of Wei to send with the transaction
    • data [data:optional]: input data
    • nonce [number]: account nonce
  2. method signature [string:optional]
    • The method signature, if present, is to aid decoding the calldata. Should consist of methodname(paramtype,...), e.g. transfer(uint256,address). The signer may use this data to parse the supplied calldata, and show the user. The data, however, is considered totally untrusted, and reliability is not expected.

Result

  • signed transaction in RLP encoded form [data]

Sample call

{
  "id": 2,
  "jsonrpc": "2.0",
  "method": "account_signTransaction",
  "params": [
    {
      "from": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db",
      "gas": "0x55555",
      "gasPrice": "0x1234",
      "input": "0xabcd",
      "nonce": "0x0",
      "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
      "value": "0x1234"
    }
  ]
}

Response

{
  "id": 2,
  "jsonrpc": "2.0",
  "error": {
    "code": -32000,
    "message": "Request denied"
  }
}

Sample call with ABI-data

{
  "id": 67,
  "jsonrpc": "2.0",
  "method": "account_signTransaction",
  "params": [
    {
      "from": "0x694267f14675d7e1b9494fd8d72fefe1755710fa",
      "gas": "0x333",
      "gasPrice": "0x1",
      "nonce": "0x0",
      "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
      "value": "0x0",
      "data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"
    },
    "safeSend(address)"
  ]
}

Response

{
  "jsonrpc": "2.0",
  "id": 67,
  "result": {
    "raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",
    "tx": {
      "nonce": "0x0",
      "gasPrice": "0x1",
      "gas": "0x333",
      "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
      "value": "0x0",
      "input": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012",
      "v": "0x26",
      "r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e",
      "s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",
      "hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e"
    }
  }
}

Bash example:

#curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/

{"jsonrpc":"2.0","id":67,"result":{"raw":"0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663","tx":{"nonce":"0x0","gasPrice":"0x1","gas":"0x333","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0","value":"0x0","input":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012","v":"0x26","r":"0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e","s":"0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663","hash":"0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e"}}}

account_signData

Sign data

Signs a chunk of data and returns the calculated signature.

Arguments

  • content type [string]: type of signed data
    • text/validator: hex data with custom validator defined in a contract
    • application/clique: clique headers
    • text/plain: simple hex data validated by account_ecRecover
  • account [address]: account to sign with
  • data [object]: data to sign

Result

  • calculated signature [data]

Sample call

{
  "id": 3,
  "jsonrpc": "2.0",
  "method": "account_signData",
  "params": [
    "data/plain",
    "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db",
    "0xaabbccdd"
  ]
}

Response

{
  "id": 3,
  "jsonrpc": "2.0",
  "result": "0x5b6693f153b48ec1c706ba4169960386dbaa6903e249cc79a8e6ddc434451d417e1e57327872c7f538beeb323c300afa9999a3d4a5de6caf3be0d5ef832b67ef1c"
}

account_signTypedData

Sign data

Signs a chunk of structured data conformant to EIP712 and returns the calculated signature.

Arguments

  • account [address]: account to sign with
  • data [object]: data to sign

Result

  • calculated signature [data]

Sample call

{
  "id": 68,
  "jsonrpc": "2.0",
  "method": "account_signTypedData",
  "params": [
    "0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826",
    {
      "types": {
        "EIP712Domain": [
          {
            "name": "name",
            "type": "string"
          },
          {
            "name": "version",
            "type": "string"
          },
          {
            "name": "chainId",
            "type": "uint256"
          },
          {
            "name": "verifyingContract",
            "type": "address"
          }
        ],
        "Person": [
          {
            "name": "name",
            "type": "string"
          },
          {
            "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",
          "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
        },
        "to": {
          "name": "Bob",
          "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
        },
        "contents": "Hello, Bob!"
      }
    }
  ]
}

Response

{
    "id": 1,
    "jsonrpc": "2.0",
    "result": "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c"
}

account_ecRecover

Sign data

Derive the address from the account that was used to sign data with content type text/plain and the signature.

Arguments

  • data [data]: data that was signed
  • signature [data]: the signature to verify

Result

  • derived account [address]

Sample call

{
  "id": 4,
  "jsonrpc": "2.0",
  "method": "account_ecRecover",
  "params": [
    "data/plain",
    "0xaabbccdd",
    "0x5b6693f153b48ec1c706ba4169960386dbaa6903e249cc79a8e6ddc434451d417e1e57327872c7f538beeb323c300afa9999a3d4a5de6caf3be0d5ef832b67ef1c"
  ]
}

Response

{
  "id": 4,
  "jsonrpc": "2.0",
  "result": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db"
}

account_import

Import account

Import a private key into the keystore. The imported key is expected to be encrypted according to the web3 keystore format.

Arguments

Result

  • imported key [object]:
    • key.address [address]: address of the imported key
    • key.type [string]: type of the account
    • key.url [string]: key URL

Sample call

{
  "id": 6,
  "jsonrpc": "2.0",
  "method": "account_import",
  "params": [
    {
      "address": "c7412fc59930fd90099c917a50e5f11d0934b2f5",
      "crypto": {
        "cipher": "aes-128-ctr",
        "cipherparams": {
          "iv": "401c39a7c7af0388491c3d3ecb39f532"
        },
        "ciphertext": "eb045260b18dd35cd0e6d99ead52f8fa1e63a6b0af2d52a8de198e59ad783204",
        "kdf": "scrypt",
        "kdfparams": {
          "dklen": 32,
          "n": 262144,
          "p": 1,
          "r": 8,
          "salt": "9a657e3618527c9b5580ded60c12092e5038922667b7b76b906496f021bb841a"
        },
        "mac": "880dc10bc06e9cec78eb9830aeb1e7a4a26b4c2c19615c94acb632992b952806"
      },
      "id": "09bccb61-b8d3-4e93-bf4f-205a8194f0b9",
      "version": 3
    }
  ]
}

Response

{
  "id": 6,
  "jsonrpc": "2.0",
  "result": {
    "address": "0xc7412fc59930fd90099c917a50e5f11d0934b2f5",
    "type": "account",
    "url": "keystore:///tmp/keystore/UTC--2017-08-24T11-00-42.032024108Z--c7412fc59930fd90099c917a50e5f11d0934b2f5"
  }
}

account_export

Export account from keystore

Export a private key from the keystore. The exported private key is encrypted with the original password. When the key is imported later this password is required.

Arguments

  • account [address]: export private key that is associated with this account

Result

Sample call

{
  "id": 5,
  "jsonrpc": "2.0",
  "method": "account_export",
  "params": [
    "0xc7412fc59930fd90099c917a50e5f11d0934b2f5"
  ]
}

Response

{
  "id": 5,
  "jsonrpc": "2.0",
  "result": {
    "address": "c7412fc59930fd90099c917a50e5f11d0934b2f5",
    "crypto": {
      "cipher": "aes-128-ctr",
      "cipherparams": {
        "iv": "401c39a7c7af0388491c3d3ecb39f532"
      },
      "ciphertext": "eb045260b18dd35cd0e6d99ead52f8fa1e63a6b0af2d52a8de198e59ad783204",
      "kdf": "scrypt",
      "kdfparams": {
        "dklen": 32,
        "n": 262144,
        "p": 1,
        "r": 8,
        "salt": "9a657e3618527c9b5580ded60c12092e5038922667b7b76b906496f021bb841a"
      },
      "mac": "880dc10bc06e9cec78eb9830aeb1e7a4a26b4c2c19615c94acb632992b952806"
    },
    "id": "09bccb61-b8d3-4e93-bf4f-205a8194f0b9",
    "version": 3
  }
}

UI API

These methods needs to be implemented by a UI listener.

By starting the signer with the switch --stdio-ui-test, the signer will invoke all known methods, and expect the UI to respond with denials. This can be used during development to ensure that the API is (at least somewhat) correctly implemented. See pythonsigner, which can be invoked via python3 pythonsigner.py test to perform the 'denial-handshake-test'.

All methods in this API uses object-based parameters, so that there can be no mixups of parameters: each piece of data is accessed by key.

See the ui API changelog for information about changes to this API.

OBS! A slight deviation from json standard is in place: every request and response should be confined to a single line. Whereas the json specification allows for linebreaks, linebreaks should not be used in this communication channel, to make things simpler for both parties.

ApproveTx / ui_approveTx

Invoked when there's a transaction for approval.

Sample call

Here's a method invocation:


curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/

Results in the following invocation on the UI:


{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "ui_approveTx",
  "params": [
    {
      "transaction": {
        "from": "0x0x694267f14675d7e1b9494fd8d72fefe1755710fa",
        "to": "0x0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
        "gas": "0x333",
        "gasPrice": "0x1",
        "value": "0x0",
        "nonce": "0x0",
        "data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012",
        "input": null
      },
      "call_info": [
          {
            "type": "WARNING",
            "message": "Invalid checksum on to-address"
          },
          {
            "type": "Info",
            "message": "safeSend(address: 0x0000000000000000000000000000000000000012)"
          }
        ],
      "meta": {
        "remote": "127.0.0.1:48486",
        "local": "localhost:8550",
        "scheme": "HTTP/1.1"
      }
    }
  ]
}

The same method invocation, but with invalid data:


curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000002000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "ui_approveTx",
  "params": [
    {
      "transaction": {
        "from": "0x0x694267f14675d7e1b9494fd8d72fefe1755710fa",
        "to": "0x0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
        "gas": "0x333",
        "gasPrice": "0x1",
        "value": "0x0",
        "nonce": "0x0",
        "data": "0x4401a6e40000000000000002000000000000000000000000000000000000000000000012",
        "input": null
      },
      "call_info": [
          {
            "type": "WARNING",
            "message": "Invalid checksum on to-address"
          },
          {
            "type": "WARNING",
            "message": "Transaction data did not match ABI-interface: WARNING: Supplied data is stuffed with extra data. \nWant 0000000000000002000000000000000000000000000000000000000000000012\nHave 0000000000000000000000000000000000000000000000000000000000000012\nfor method safeSend(address)"
          }
        ],
      "meta": {
        "remote": "127.0.0.1:48492",
        "local": "localhost:8550",
        "scheme": "HTTP/1.1"
      }
    }
  ]
}


One which has missing to, but with no data:


{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "ui_approveTx",
  "params": [
    {
      "transaction": {
        "from": "",
        "to": null,
        "gas": "0x0",
        "gasPrice": "0x0",
        "value": "0x0",
        "nonce": "0x0",
        "data": null,
        "input": null
      },
      "call_info": [
          {
            "type": "CRITICAL",
            "message": "Tx will create contract with empty code!"
          }
        ],
      "meta": {
        "remote": "signer binary",
        "local": "main",
        "scheme": "in-proc"
      }
    }
  ]
}

ApproveListing / ui_approveListing

Invoked when a request for account listing has been made.

Sample call


{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "ui_approveListing",
  "params": [
    {
      "accounts": [
        {
          "type": "Account",
          "url": "keystore:///home/bazonk/.ethereum/keystore/UTC--2017-11-20T14-44-54.089682944Z--123409812340981234098123409812deadbeef42",
          "address": "0x123409812340981234098123409812deadbeef42"
        },
        {
          "type": "Account",
          "url": "keystore:///home/bazonk/.ethereum/keystore/UTC--2017-11-23T21-59-03.199240693Z--cafebabedeadbeef34098123409812deadbeef42",
          "address": "0xcafebabedeadbeef34098123409812deadbeef42"
        }
      ],
      "meta": {
        "remote": "signer binary",
        "local": "main",
        "scheme": "in-proc"
      }
    }
  ]
}

ApproveSignData / ui_approveSignData

Sample call

{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "ui_approveSignData",
  "params": [
    {
      "address": "0x123409812340981234098123409812deadbeef42",
      "raw_data": "0x01020304",
      "message": "\u0019Ethereum Signed Message:\n4\u0001\u0002\u0003\u0004",
      "hash": "0x7e3a4e7a9d1744bc5c675c25e1234ca8ed9162bd17f78b9085e48047c15ac310",
      "meta": {
        "remote": "signer binary",
        "local": "main",
        "scheme": "in-proc"
      }
    }
  ]
}

ShowInfo / ui_showInfo

The UI should show the info to the user. Does not expect response.

Sample call

{
  "jsonrpc": "2.0",
  "id": 9,
  "method": "ui_showInfo",
  "params": [
    {
      "text": "Tests completed"
    }
  ]
}

ShowError / ui_showError

The UI should show the info to the user. Does not expect response.


{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "ShowError",
  "params": [
    {
      "text": "Testing 'ShowError'"
    }
  ]
}

OnApprovedTx / ui_onApprovedTx

OnApprovedTx is called when a transaction has been approved and signed. The call contains the return value that will be sent to the external caller. The return value from this method is ignored - the reason for having this callback is to allow the ruleset to keep track of approved transactions.

When implementing rate-limited rules, this callback should be used.

TLDR; Use this method to keep track of signed transactions, instead of using the data in ApproveTx.

OnSignerStartup / ui_onSignerStartup

This method provide the UI with information about what API version the signer uses (both internal and external) aswell as build-info and external API, in k/v-form.

Example call:


{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "ui_onSignerStartup",
  "params": [
    {
      "info": {
        "extapi_http": "http://localhost:8550",
        "extapi_ipc": null,
        "extapi_version": "2.0.0",
        "intapi_version": "1.2.0"
      }
    }
  ]
}

Rules for UI apis

A UI should conform to the following rules.

  • A UI MUST NOT load any external resources that were not embedded/part of the UI package.
    • For example, not load icons, stylesheets from the internet
    • Not load files from the filesystem, unless they reside in the same local directory (e.g. config files)
  • A Graphical UI MUST show the blocky-identicon for ethereum addresses.
  • A UI MUST warn display appropriate warning if the destination-account is formatted with invalid checksum.
  • A UI MUST NOT open any ports or services
    • The signer opens the public port
  • A UI SHOULD verify the permissions on the signer binary, and refuse to execute or warn if permissions allow non-user write.
  • A UI SHOULD inform the user about the SHA256 or MD5 hash of the binary being executed
  • A UI SHOULD NOT maintain a secondary storage of data, e.g. list of accounts
    • The signer provides accounts
  • A UI SHOULD, to the best extent possible, use static linking / bundling, so that required libraries are bundled along with the UI.

UI Implementations

There are a couple of implementation for a UI. We'll try to keep this list up to date.

Name Repo UI type No external resources Blocky support Verifies permissions Hash information No secondary storage Statically linked Can modify parameters
QtSigner https://github.com/holiman/qtsigner/ Python3/QT-based 👍 👍 👍 👍 👍 👍 (partially)
GtkSigner https://github.com/holiman/gtksigner Python3/GTK-based 👍 👍 👍
Frame https://github.com/floating/frame/commits/go-signer Electron-based ?
Clef UI https://github.com/kyokan/clef-ui Golang/QT-based 👍 👍 👍 👍 👍 (approve tx only)