Skip to content

Commit 43e8efe

Browse files
authored
accounts, eth, clique, signer: support for external signer API (#18079)
* accounts, eth, clique: implement external backend + move sighash calc to backend * signer: implement account_Version on external API * accounts/external: enable ipc, add copyright * accounts, internal, signer: formatting * node: go fmt * flags: disallow --dev in combo with --externalsigner * accounts: remove clique-specific signing method, replace with more generic * accounts, consensus: formatting + fix error in tests * signer/core: remove (test-) import cycle * clique: remove unused import * accounts: remove CliqueHash and avoid dependency on package crypto * consensus/clique: unduplicate header encoding
1 parent 520024d commit 43e8efe

17 files changed

Lines changed: 458 additions & 115 deletions

File tree

‎accounts/accounts.go‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,14 @@
1818
package accounts
1919

2020
import (
21+
"fmt"
2122
"math/big"
2223

2324
ethereum "github.com/ethereum/go-ethereum"
2425
"github.com/ethereum/go-ethereum/common"
2526
"github.com/ethereum/go-ethereum/core/types"
2627
"github.com/ethereum/go-ethereum/event"
28+
"golang.org/x/crypto/sha3"
2729
)
2830

2931
// Account represents an Ethereum account located at a specific location defined
@@ -87,8 +89,20 @@ type Wallet interface {
8789
// chain state reader.
8890
SelfDerive(base DerivationPath, chain ethereum.ChainStateReader)
8991

90-
// SignHash requests the wallet to sign the given hash.
92+
// SignData requests the wallet to sign the hash of the given data
93+
// It looks up the account specified either solely via its address contained within,
94+
// or optionally with the aid of any location metadata from the embedded URL field.
9195
//
96+
// If the wallet requires additional authentication to sign the request (e.g.
97+
// a password to decrypt the account, or a PIN code o verify the transaction),
98+
// an AuthNeededError instance will be returned, containing infos for the user
99+
// about which fields or actions are needed. The user may retry by providing
100+
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
101+
// the account in a keystore).
102+
SignData(account Account, mimeType string, data []byte) ([]byte, error)
103+
104+
// Signtext requests the wallet to sign the hash of a given piece of data, prefixed
105+
// by the Ethereum prefix scheme
92106
// It looks up the account specified either solely via its address contained within,
93107
// or optionally with the aid of any location metadata from the embedded URL field.
94108
//
@@ -98,7 +112,7 @@ type Wallet interface {
98112
// about which fields or actions are needed. The user may retry by providing
99113
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
100114
// the account in a keystore).
101-
SignHash(account Account, hash []byte) ([]byte, error)
115+
SignText(account Account, text []byte) ([]byte, error)
102116

103117
// SignTx requests the wallet to sign the given transaction.
104118
//
@@ -113,12 +127,12 @@ type Wallet interface {
113127
// the account in a keystore).
114128
SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
115129

116-
// SignHashWithPassphrase requests the wallet to sign the given hash with the
130+
// SignTextWithPassphrase requests the wallet to sign the given text with the
117131
// given passphrase as extra authentication information.
118132
//
119133
// It looks up the account specified either solely via its address contained within,
120134
// or optionally with the aid of any location metadata from the embedded URL field.
121-
SignHashWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
135+
SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
122136

123137
// SignTxWithPassphrase requests the wallet to sign the given transaction, with the
124138
// given passphrase as extra authentication information.
@@ -148,6 +162,19 @@ type Backend interface {
148162
Subscribe(sink chan<- WalletEvent) event.Subscription
149163
}
150164

165+
// TextHash is a helper function that calculates a hash for the given message that can be
166+
// safely used to calculate a signature from.
167+
//
168+
// The hash is calulcated as
169+
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
170+
//
171+
// This gives context to the signed message and prevents signing of transactions.
172+
func TextHash(data []byte) []byte {
173+
hash := sha3.NewLegacyKeccak256()
174+
fmt.Fprintf(hash, "\x19Ethereum Signed Message:\n%d%s", len(data), data)
175+
return hash.Sum(nil)
176+
}
177+
151178
// WalletEventType represents the different event types that can be fired by
152179
// the wallet subscription subsystem.
153180
type WalletEventType int

‎accounts/accounts_test.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2019 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package accounts
18+
19+
import (
20+
"bytes"
21+
"testing"
22+
23+
"github.com/ethereum/go-ethereum/common/hexutil"
24+
)
25+
26+
func TestTextHash(t *testing.T) {
27+
hash := TextHash([]byte("Hello Joe"))
28+
want := hexutil.MustDecode("0xa080337ae51c4e064c189e113edd0ba391df9206e2f49db658bb32cf2911730b")
29+
if !bytes.Equal(hash, want) {
30+
t.Fatalf("wrong hash: %x", hash)
31+
}
32+
}

‎accounts/external/backend.go‎

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// Copyright 2018 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// go-ethereum is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package external
18+
19+
import (
20+
"fmt"
21+
"math/big"
22+
"sync"
23+
24+
"github.com/ethereum/go-ethereum"
25+
"github.com/ethereum/go-ethereum/accounts"
26+
"github.com/ethereum/go-ethereum/common"
27+
"github.com/ethereum/go-ethereum/common/hexutil"
28+
"github.com/ethereum/go-ethereum/core/types"
29+
"github.com/ethereum/go-ethereum/crypto"
30+
"github.com/ethereum/go-ethereum/event"
31+
"github.com/ethereum/go-ethereum/internal/ethapi"
32+
"github.com/ethereum/go-ethereum/log"
33+
"github.com/ethereum/go-ethereum/rpc"
34+
"github.com/ethereum/go-ethereum/signer/core"
35+
)
36+
37+
type ExternalBackend struct {
38+
signers []accounts.Wallet
39+
}
40+
41+
func (eb *ExternalBackend) Wallets() []accounts.Wallet {
42+
return eb.signers
43+
}
44+
45+
func NewExternalBackend(endpoint string) (*ExternalBackend, error) {
46+
signer, err := NewExternalSigner(endpoint)
47+
if err != nil {
48+
return nil, err
49+
}
50+
return &ExternalBackend{
51+
signers: []accounts.Wallet{signer},
52+
}, nil
53+
}
54+
55+
func (eb *ExternalBackend) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
56+
return event.NewSubscription(func(quit <-chan struct{}) error {
57+
<-quit
58+
return nil
59+
})
60+
}
61+
62+
// ExternalSigner provides an API to interact with an external signer (clef)
63+
// It proxies request to the external signer while forwarding relevant
64+
// request headers
65+
type ExternalSigner struct {
66+
client *rpc.Client
67+
endpoint string
68+
status string
69+
cacheMu sync.RWMutex
70+
cache []accounts.Account
71+
}
72+
73+
func NewExternalSigner(endpoint string) (*ExternalSigner, error) {
74+
client, err := rpc.Dial(endpoint)
75+
if err != nil {
76+
return nil, err
77+
}
78+
extsigner := &ExternalSigner{
79+
client: client,
80+
endpoint: endpoint,
81+
}
82+
// Check if reachable
83+
version, err := extsigner.pingVersion()
84+
if err != nil {
85+
return nil, err
86+
}
87+
extsigner.status = fmt.Sprintf("ok [version=%v]", version)
88+
return extsigner, nil
89+
}
90+
91+
func (api *ExternalSigner) URL() accounts.URL {
92+
return accounts.URL{
93+
Scheme: "extapi",
94+
Path: api.endpoint,
95+
}
96+
}
97+
98+
func (api *ExternalSigner) Status() (string, error) {
99+
return api.status, nil
100+
}
101+
102+
func (api *ExternalSigner) Open(passphrase string) error {
103+
return fmt.Errorf("operation not supported on external signers")
104+
}
105+
106+
func (api *ExternalSigner) Close() error {
107+
return fmt.Errorf("operation not supported on external signers")
108+
}
109+
110+
func (api *ExternalSigner) Accounts() []accounts.Account {
111+
var accnts []accounts.Account
112+
res, err := api.listAccounts()
113+
if err != nil {
114+
log.Error("account listing failed", "error", err)
115+
return accnts
116+
}
117+
for _, addr := range res {
118+
accnts = append(accnts, accounts.Account{
119+
URL: accounts.URL{
120+
Scheme: "extapi",
121+
Path: api.endpoint,
122+
},
123+
Address: addr,
124+
})
125+
}
126+
api.cacheMu.Lock()
127+
api.cache = accnts
128+
api.cacheMu.Unlock()
129+
return accnts
130+
}
131+
132+
func (api *ExternalSigner) Contains(account accounts.Account) bool {
133+
api.cacheMu.RLock()
134+
defer api.cacheMu.RUnlock()
135+
for _, a := range api.cache {
136+
if a.Address == account.Address && (account.URL == (accounts.URL{}) || account.URL == api.URL()) {
137+
return true
138+
}
139+
}
140+
return false
141+
}
142+
143+
func (api *ExternalSigner) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) {
144+
return accounts.Account{}, fmt.Errorf("operation not supported on external signers")
145+
}
146+
147+
func (api *ExternalSigner) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
148+
log.Error("operation SelfDerive not supported on external signers")
149+
}
150+
151+
func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]byte, error) {
152+
return []byte{}, fmt.Errorf("operation not supported on external signers")
153+
}
154+
155+
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
156+
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))
160+
}
161+
162+
func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) {
163+
return api.signHash(account, accounts.TextHash(text))
164+
}
165+
166+
func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
167+
res := ethapi.SignTransactionResult{}
168+
to := common.NewMixedcaseAddress(*tx.To())
169+
data := hexutil.Bytes(tx.Data())
170+
args := &core.SendTxArgs{
171+
Data: &data,
172+
Nonce: hexutil.Uint64(tx.Nonce()),
173+
Value: hexutil.Big(*tx.Value()),
174+
Gas: hexutil.Uint64(tx.Gas()),
175+
GasPrice: hexutil.Big(*tx.GasPrice()),
176+
To: &to,
177+
From: common.NewMixedcaseAddress(account.Address),
178+
}
179+
180+
if err := api.client.Call(&res, "account_signTransaction", args); err != nil {
181+
return nil, err
182+
}
183+
return res.Tx, nil
184+
}
185+
186+
func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
187+
return []byte{}, fmt.Errorf("operation not supported on external signers")
188+
}
189+
190+
func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
191+
return nil, fmt.Errorf("operation not supported on external signers")
192+
}
193+
194+
func (api *ExternalSigner) listAccounts() ([]common.Address, error) {
195+
var res []common.Address
196+
if err := api.client.Call(&res, "account_list"); err != nil {
197+
return nil, err
198+
}
199+
return res, nil
200+
}
201+
202+
func (api *ExternalSigner) signCliqueBlock(a common.Address, rlpBlock hexutil.Bytes) (hexutil.Bytes, error) {
203+
var sig hexutil.Bytes
204+
if err := api.client.Call(&sig, "account_signData", "application/clique", a, rlpBlock); err != nil {
205+
return nil, err
206+
}
207+
if sig[64] != 27 && sig[64] != 28 {
208+
return nil, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
209+
}
210+
sig[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use
211+
return sig, nil
212+
}
213+
214+
func (api *ExternalSigner) pingVersion() (string, error) {
215+
var v string
216+
if err := api.client.Call(&v, "account_version"); err != nil {
217+
return "", err
218+
}
219+
return v, nil
220+
}

‎accounts/keystore/wallet.go‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
ethereum "github.com/ethereum/go-ethereum"
2323
"github.com/ethereum/go-ethereum/accounts"
2424
"github.com/ethereum/go-ethereum/core/types"
25+
"github.com/ethereum/go-ethereum/crypto"
2526
)
2627

2728
// keystoreWallet implements the accounts.Wallet interface for the original
@@ -78,11 +79,11 @@ func (w *keystoreWallet) Derive(path accounts.DerivationPath, pin bool) (account
7879
// there is no notion of hierarchical account derivation for plain keystore accounts.
7980
func (w *keystoreWallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {}
8081

81-
// SignHash implements accounts.Wallet, attempting to sign the given hash with
82+
// signHash attempts to sign the given hash with
8283
// the given account. If the wallet does not wrap this particular account, an
8384
// error is returned to avoid account leakage (even though in theory we may be
8485
// able to sign via our shared keystore backend).
85-
func (w *keystoreWallet) SignHash(account accounts.Account, hash []byte) ([]byte, error) {
86+
func (w *keystoreWallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
8687
// Make sure the requested account is contained within
8788
if !w.Contains(account) {
8889
return nil, accounts.ErrUnknownAccount
@@ -91,6 +92,15 @@ func (w *keystoreWallet) SignHash(account accounts.Account, hash []byte) ([]byte
9192
return w.keystore.SignHash(account, hash)
9293
}
9394

95+
// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
96+
func (w *keystoreWallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
97+
return w.signHash(account, crypto.Keccak256(data))
98+
}
99+
100+
func (w *keystoreWallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
101+
return w.signHash(account, accounts.TextHash(text))
102+
}
103+
94104
// SignTx implements accounts.Wallet, attempting to sign the given transaction
95105
// with the given account. If the wallet does not wrap this particular account,
96106
// an error is returned to avoid account leakage (even though in theory we may
@@ -106,13 +116,13 @@ func (w *keystoreWallet) SignTx(account accounts.Account, tx *types.Transaction,
106116

107117
// SignHashWithPassphrase implements accounts.Wallet, attempting to sign the
108118
// given hash with the given account using passphrase as extra authentication.
109-
func (w *keystoreWallet) SignHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
119+
func (w *keystoreWallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
110120
// Make sure the requested account is contained within
111121
if !w.Contains(account) {
112122
return nil, accounts.ErrUnknownAccount
113123
}
114124
// Account seems valid, request the keystore to sign
115-
return w.keystore.SignHashWithPassphrase(account, passphrase, hash)
125+
return w.keystore.SignHashWithPassphrase(account, passphrase, accounts.TextHash(text))
116126
}
117127

118128
// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given

0 commit comments

Comments
 (0)