Skip to content

Commit 75d292b

Browse files
authored
clef: external signing fixes + signing data (#19003)
* signer/clef: make use of json-rpc notification * signer: tidy up output of OnApprovedTx * accounts/external, signer: implement remote signing of text, make accounts_sign take hexdata * clef: added basic testscript * signer, external, api: add clique signing test to debug rpc, fix clique signing in clef * signer: fix clique interoperability between geth and clef * clef: rename networkid switch to chainid * clef: enable chainid flag * clef, signer: minor changes from review * clef: more tests for signer
1 parent edf976e commit 75d292b

10 files changed

Lines changed: 240 additions & 73 deletions

File tree

‎accounts/external/backend.go‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import (
2626
"github.com/ethereum/go-ethereum/common"
2727
"github.com/ethereum/go-ethereum/common/hexutil"
2828
"github.com/ethereum/go-ethereum/core/types"
29-
"github.com/ethereum/go-ethereum/crypto"
3029
"github.com/ethereum/go-ethereum/event"
3130
"github.com/ethereum/go-ethereum/internal/ethapi"
3231
"github.com/ethereum/go-ethereum/log"
@@ -154,13 +153,31 @@ func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]by
154153

155154
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
156155
func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
157-
// TODO! Replace this with a call to clef SignData with correct mime-type for Clique, once we
158-
// have that in place
159-
return api.signHash(account, crypto.Keccak256(data))
156+
var res hexutil.Bytes
157+
var signAddress = common.NewMixedcaseAddress(account.Address)
158+
if err := api.client.Call(&res, "account_signData",
159+
mimeType,
160+
&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
161+
hexutil.Encode(data)); err != nil {
162+
return nil, err
163+
}
164+
// If V is on 27/28-form, convert to to 0/1 for Clique
165+
if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) {
166+
res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
167+
}
168+
return res, nil
160169
}
161170

162171
func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
163-
return api.signHash(account, accounts.TextHash(text))
172+
var res hexutil.Bytes
173+
var signAddress = common.NewMixedcaseAddress(account.Address)
174+
if err := api.client.Call(&res, "account_signData",
175+
accounts.MimetypeTextPlain,
176+
&signAddress, // Need to use the pointer here, because of how MarshalJSON is defined
177+
hexutil.Encode(text)); err != nil {
178+
return nil, err
179+
}
180+
return res, nil
164181
}
165182

166183
func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
@@ -202,18 +219,6 @@ func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
202219
return res, nil
203220
}
204221

205-
func (api *ExternalSigner) signCliqueBlock(a common.Address, rlpBlock hexutil.Bytes) (hexutil.Bytes, error) {
206-
var sig hexutil.Bytes
207-
if err := api.client.Call(&sig, "account_signData", core.ApplicationClique.Mime, a, rlpBlock); err != nil {
208-
return nil, err
209-
}
210-
if sig[64] != 27 && sig[64] != 28 {
211-
return nil, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
212-
}
213-
sig[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
214-
return sig, nil
215-
}
216-
217222
func (api *ExternalSigner) pingVersion() (string, error) {
218223
var v string
219224
if err := api.client.Call(&v, "account_version"); err != nil {

‎cmd/clef/intapi_changelog.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
### Changelog for internal API (ui-api)
22

3+
### 3.2.0
4+
5+
* Make `ShowError`, `OnApprovedTx`, `OnSignerStartup` be json-rpc [notifications](https://www.jsonrpc.org/specification#notification):
6+
7+
> A Notification is a Request object without an "id" member. A Request object that is a Notification signifies the Client's lack of interest in the corresponding Response object, and as such no Response object needs to be returned to the client. The Server MUST NOT reply to a Notification, including those that are within a batch request.
8+
>
9+
> Notifications are not confirmable by definition, since they do not have a Response object to be returned. As such, the Client would not be aware of any errors (like e.g. "Invalid params","Internal error"
310
### 3.1.0
411

5-
* Add `ContentType string` to `SignDataRequest` to accommodate the latest EIP-191 and EIP-712 implementations.
12+
* Add `ContentType` `string` to `SignDataRequest` to accommodate the latest EIP-191 and EIP-712 implementations.
613

714
### 3.0.0
815

‎cmd/clef/main.go‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import (
4444
"github.com/ethereum/go-ethereum/crypto"
4545
"github.com/ethereum/go-ethereum/log"
4646
"github.com/ethereum/go-ethereum/node"
47+
"github.com/ethereum/go-ethereum/params"
4748
"github.com/ethereum/go-ethereum/rlp"
4849
"github.com/ethereum/go-ethereum/rpc"
4950
"github.com/ethereum/go-ethereum/signer/core"
@@ -83,6 +84,11 @@ var (
8384
Value: DefaultConfigDir(),
8485
Usage: "Directory for Clef configuration",
8586
}
87+
chainIdFlag = cli.Int64Flag{
88+
Name: "chainid",
89+
Value: params.MainnetChainConfig.ChainID.Int64(),
90+
Usage: "Chain id to use for signing (1=mainnet, 3=ropsten, 4=rinkeby, 5=Goerli)",
91+
}
8692
rpcPortFlag = cli.IntFlag{
8793
Name: "rpcport",
8894
Usage: "HTTP-RPC server listening port",
@@ -178,7 +184,7 @@ func init() {
178184
logLevelFlag,
179185
keystoreFlag,
180186
configdirFlag,
181-
utils.NetworkIdFlag,
187+
chainIdFlag,
182188
utils.LightKDFFlag,
183189
utils.NoUSBFlag,
184190
utils.RPCListenAddrFlag,
@@ -402,9 +408,13 @@ func signer(c *cli.Context) error {
402408
}
403409
}
404410
}
411+
log.Info("Starting signer", "chainid", c.GlobalInt64(chainIdFlag.Name),
412+
"keystore", c.GlobalString(keystoreFlag.Name),
413+
"light-kdf", c.GlobalBool(utils.LightKDFFlag.Name),
414+
"advanced", c.GlobalBool(advancedMode.Name))
405415

406416
apiImpl := core.NewSignerAPI(
407-
c.GlobalInt64(utils.NetworkIdFlag.Name),
417+
c.GlobalInt64(chainIdFlag.Name),
408418
c.GlobalString(keystoreFlag.Name),
409419
c.GlobalBool(utils.NoUSBFlag.Name),
410420
ui, db,

‎cmd/clef/tests/testsigner.js‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// This file is a test-utility for testing clef-functionality
2+
//
3+
// Start clef with
4+
//
5+
// build/bin/clef --4bytedb=./cmd/clef/4byte.json --rpc
6+
//
7+
// Start geth with
8+
//
9+
// build/bin/geth --nodiscover --maxpeers 0 --signer http://localhost:8550 console --preload=cmd/clef/tests/testsigner.js
10+
//
11+
// and in the console simply invoke
12+
//
13+
// > test()
14+
//
15+
// You can reload the file via `reload()`
16+
17+
function reload(){
18+
loadScript("./cmd/clef/tests/testsigner.js");
19+
}
20+
21+
function init(){
22+
if (typeof accts == 'undefined' || accts.length == 0){
23+
accts = eth.accounts
24+
console.log("Got accounts ", accts);
25+
}
26+
}
27+
init()
28+
function testTx(){
29+
if( accts && accts.length > 0) {
30+
var a = accts[0]
31+
var txdata = eth.signTransaction({from: a, to: a, value: 1, nonce: 1, gas: 1, gasPrice: 1})
32+
var v = parseInt(txdata.tx.v)
33+
console.log("V value: ", v)
34+
if (v == 37 || v == 38){
35+
console.log("Mainnet 155-protected chainid was used")
36+
}
37+
if (v == 27 || v == 28){
38+
throw new Error("Mainnet chainid was used, but without replay protection!")
39+
}
40+
}
41+
}
42+
function testSignText(){
43+
if( accts && accts.length > 0){
44+
var a = accts[0]
45+
var r = eth.sign(a, "0x68656c6c6f20776f726c64"); //hello world
46+
console.log("signing response", r)
47+
}
48+
}
49+
function testClique(){
50+
if( accts && accts.length > 0){
51+
var a = accts[0]
52+
var r = debug.testSignCliqueBlock(a, 0); // Sign genesis
53+
console.log("signing response", r)
54+
if( a != r){
55+
throw new Error("Requested signing by "+a+ " but got sealer "+r)
56+
}
57+
}
58+
}
59+
60+
function test(){
61+
var tests = [
62+
testTx,
63+
testSignText,
64+
testClique,
65+
]
66+
for( i in tests){
67+
try{
68+
tests[i]()
69+
}catch(err){
70+
console.log(err)
71+
}
72+
}
73+
}

‎internal/ethapi/api.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import (
3131
"github.com/ethereum/go-ethereum/common"
3232
"github.com/ethereum/go-ethereum/common/hexutil"
3333
"github.com/ethereum/go-ethereum/common/math"
34+
"github.com/ethereum/go-ethereum/consensus/clique"
3435
"github.com/ethereum/go-ethereum/consensus/ethash"
3536
"github.com/ethereum/go-ethereum/core"
3637
"github.com/ethereum/go-ethereum/core/rawdb"
@@ -1469,6 +1470,45 @@ func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (stri
14691470
return fmt.Sprintf("%x", encoded), nil
14701471
}
14711472

1473+
// TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
1474+
// given address, returning the address of the recovered signature
1475+
//
1476+
// This is a temporary method to debug the externalsigner integration,
1477+
// TODO: Remove this method when the integration is mature
1478+
func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
1479+
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
1480+
if block == nil {
1481+
return common.Address{}, fmt.Errorf("block #%d not found", number)
1482+
}
1483+
header := block.Header()
1484+
header.Extra = make([]byte, 32+65)
1485+
encoded := clique.CliqueRLP(header)
1486+
1487+
// Look up the wallet containing the requested signer
1488+
account := accounts.Account{Address: address}
1489+
wallet, err := api.b.AccountManager().Find(account)
1490+
if err != nil {
1491+
return common.Address{}, err
1492+
}
1493+
1494+
signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
1495+
if err != nil {
1496+
return common.Address{}, err
1497+
}
1498+
sealHash := clique.SealHash(header).Bytes()
1499+
log.Info("test signing of clique block",
1500+
"Sealhash", fmt.Sprintf("%x", sealHash),
1501+
"signature", fmt.Sprintf("%x", signature))
1502+
pubkey, err := crypto.Ecrecover(sealHash, signature)
1503+
if err != nil {
1504+
return common.Address{}, err
1505+
}
1506+
var signer common.Address
1507+
copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
1508+
1509+
return signer, nil
1510+
}
1511+
14721512
// PrintBlock retrieves a block and returns its pretty printed form.
14731513
func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
14741514
block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))

‎internal/web3ext/web3ext.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,12 @@ web3._extend({
231231
call: 'debug_getBlockRlp',
232232
params: 1
233233
}),
234+
new web3._extend.Method({
235+
name: 'testSignCliqueBlock',
236+
call: 'debug_testSignCliqueBlock',
237+
params: 2,
238+
inputFormatters: [web3._extend.formatters.inputAddressFormatter, null],
239+
}),
234240
new web3._extend.Method({
235241
name: 'setHead',
236242
call: 'debug_setHead',

‎signer/core/api.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const (
4141
// ExternalAPIVersion -- see extapi_changelog.md
4242
ExternalAPIVersion = "5.0.0"
4343
// InternalAPIVersion -- see intapi_changelog.md
44-
InternalAPIVersion = "3.1.0"
44+
InternalAPIVersion = "3.2.0"
4545
)
4646

4747
// ExternalAPI defines the external API through which signing requests are made.

‎signer/core/cliui.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ package core
1818

1919
import (
2020
"bufio"
21+
"encoding/json"
2122
"fmt"
2223
"os"
2324
"strings"
2425
"sync"
2526

26-
"github.com/davecgh/go-spew/spew"
2727
"github.com/ethereum/go-ethereum/common/hexutil"
2828
"github.com/ethereum/go-ethereum/internal/ethapi"
2929
"github.com/ethereum/go-ethereum/log"
@@ -264,7 +264,11 @@ func (ui *CommandlineUI) ShowInfo(message string) {
264264

265265
func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) {
266266
fmt.Printf("Transaction signed:\n ")
267-
spew.Dump(tx.Tx)
267+
if jsn, err := json.MarshalIndent(tx.Tx, " ", " "); err != nil {
268+
fmt.Printf("WARN: marshalling error %v\n", err)
269+
} else {
270+
fmt.Println(string(jsn))
271+
}
268272
}
269273

270274
func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) {

0 commit comments

Comments
 (0)