Skip to content

Commit b59c839

Browse files
bas-vkfjl
authored andcommitted
internal/ethapi: add personal_sign and fix eth_sign to hash message (bnb-chain#2940)
This commit includes several API changes: - The behavior of eth_sign is changed. It now accepts an arbitrary message, prepends the well-known string \x19Ethereum Signed Message:\n<length of message> hashes the result using keccak256 and calculates the signature of the hash. This breaks backwards compatability! - personal_sign(hash, address [, password]) is added. It has the same semantics as eth_sign but also accepts a password. The private key used to sign the hash is temporarily unlocked in the scope of the request. - personal_recover(message, signature) is added and returns the address for the account that created a signature.
1 parent 289b307 commit b59c839

13 files changed

Lines changed: 220 additions & 34 deletions

File tree

‎accounts/abi/bind/auth.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
5252
if address != keyAddr {
5353
return nil, errors.New("not authorized to sign this account")
5454
}
55-
signature, err := crypto.Sign(tx.SigHash().Bytes(), key)
55+
signature, err := crypto.SignEthereum(tx.SigHash().Bytes(), key)
5656
if err != nil {
5757
return nil, err
5858
}

‎accounts/account_manager.go‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,11 @@ func (am *Manager) DeleteAccount(a Account, passphrase string) error {
136136
return err
137137
}
138138

139-
// Sign signs hash with an unlocked private key matching the given address.
140-
func (am *Manager) Sign(addr common.Address, hash []byte) (signature []byte, err error) {
139+
// Sign calculates a ECDSA signature for the given hash.
140+
// Note, Ethereum signatures have a particular format as described in the
141+
// yellow paper. Use the SignEthereum function to calculate a signature
142+
// in Ethereum format.
143+
func (am *Manager) Sign(addr common.Address, hash []byte) ([]byte, error) {
141144
am.mu.RLock()
142145
defer am.mu.RUnlock()
143146
unlockedKey, found := am.unlocked[addr]
@@ -147,16 +150,28 @@ func (am *Manager) Sign(addr common.Address, hash []byte) (signature []byte, err
147150
return crypto.Sign(hash, unlockedKey.PrivateKey)
148151
}
149152

150-
// SignWithPassphrase signs hash if the private key matching the given address can be
151-
// decrypted with the given passphrase.
153+
// SignEthereum calculates a ECDSA signature for the given hash.
154+
// The signature has the format as described in the Ethereum yellow paper.
155+
func (am *Manager) SignEthereum(addr common.Address, hash []byte) ([]byte, error) {
156+
am.mu.RLock()
157+
defer am.mu.RUnlock()
158+
unlockedKey, found := am.unlocked[addr]
159+
if !found {
160+
return nil, ErrLocked
161+
}
162+
return crypto.SignEthereum(hash, unlockedKey.PrivateKey)
163+
}
164+
165+
// SignWithPassphrase signs hash if the private key matching the given
166+
// address can be decrypted with the given passphrase.
152167
func (am *Manager) SignWithPassphrase(addr common.Address, passphrase string, hash []byte) (signature []byte, err error) {
153168
_, key, err := am.getDecryptedKey(Account{Address: addr}, passphrase)
154169
if err != nil {
155170
return nil, err
156171
}
157172

158173
defer zeroKey(key.PrivateKey)
159-
return crypto.Sign(hash, key.PrivateKey)
174+
return crypto.SignEthereum(hash, key.PrivateKey)
160175
}
161176

162177
// Unlock unlocks the given account indefinitely.

‎common/bytes.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func ToHex(b []byte) string {
3737

3838
func FromHex(s string) []byte {
3939
if len(s) > 1 {
40-
if s[0:2] == "0x" {
40+
if s[0:2] == "0x" || s[0:2] == "0X" {
4141
s = s[2:]
4242
}
4343
if len(s)%2 == 1 {

‎common/registrar/ethreg/api.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ func (be *registryAPIBackend) Transact(fromStr, toStr, nonceStr, valueStr, gasSt
257257
tx = types.NewTransaction(nonce, to, value, gas, price, data)
258258
}
259259

260-
signature, err := be.am.Sign(from, tx.SigHash().Bytes())
260+
signature, err := be.am.SignEthereum(from, tx.SigHash().Bytes())
261261
if err != nil {
262262
return "", err
263263
}

‎console/bridge.go‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,44 @@ func (b *bridge) UnlockAccount(call otto.FunctionCall) (response otto.Value) {
126126
return val
127127
}
128128

129+
// Sign is a wrapper around the personal.sign RPC method that uses a non-echoing password
130+
// prompt to aquire the passphrase and executes the original RPC method (saved in
131+
// jeth.sign) with it to actually execute the RPC call.
132+
func (b *bridge) Sign(call otto.FunctionCall) (response otto.Value) {
133+
var (
134+
message = call.Argument(0)
135+
account = call.Argument(1)
136+
passwd = call.Argument(2)
137+
)
138+
139+
if !message.IsString() {
140+
throwJSException("first argument must be the message to sign")
141+
}
142+
if !account.IsString() {
143+
throwJSException("second argument must be the account to sign with")
144+
}
145+
146+
// if the password is not given or null ask the user and ensure password is a string
147+
if passwd.IsUndefined() || passwd.IsNull() {
148+
fmt.Fprintf(b.printer, "Give password for account %s\n", account)
149+
if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil {
150+
throwJSException(err.Error())
151+
} else {
152+
passwd, _ = otto.ToValue(input)
153+
}
154+
}
155+
if !passwd.IsString() {
156+
throwJSException("third argument must be the password to unlock the account")
157+
}
158+
159+
// Send the request to the backend and return
160+
val, err := call.Otto.Call("jeth.sign", nil, message, account, passwd)
161+
if err != nil {
162+
throwJSException(err.Error())
163+
}
164+
return val
165+
}
166+
129167
// Sleep will block the console for the specified number of seconds.
130168
func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) {
131169
if call.Argument(0).IsNumber() {

‎console/console.go‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,19 +156,22 @@ func (c *Console) init(preload []string) error {
156156
if err != nil {
157157
return err
158158
}
159-
// Override the unlockAccount and newAccount methods since these require user interaction.
160-
// Assign the jeth.unlockAccount and jeth.newAccount in the Console the original web3 callbacks.
161-
// These will be called by the jeth.* methods after they got the password from the user and send
162-
// the original web3 request to the backend.
159+
// Override the unlockAccount, newAccount and sign methods since these require user interaction.
160+
// Assign these method in the Console the original web3 callbacks. These will be called by the jeth.*
161+
// methods after they got the password from the user and send the original web3 request to the backend.
163162
if obj := personal.Object(); obj != nil { // make sure the personal api is enabled over the interface
164163
if _, err = c.jsre.Run(`jeth.unlockAccount = personal.unlockAccount;`); err != nil {
165164
return fmt.Errorf("personal.unlockAccount: %v", err)
166165
}
167166
if _, err = c.jsre.Run(`jeth.newAccount = personal.newAccount;`); err != nil {
168167
return fmt.Errorf("personal.newAccount: %v", err)
169168
}
169+
if _, err = c.jsre.Run(`jeth.sign = personal.sign;`); err != nil {
170+
return fmt.Errorf("personal.sign: %v", err)
171+
}
170172
obj.Set("unlockAccount", bridge.UnlockAccount)
171173
obj.Set("newAccount", bridge.NewAccount)
174+
obj.Set("sign", bridge.Sign)
172175
}
173176
}
174177
// The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.

‎core/types/block_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func TestBlockEncoding(t *testing.T) {
5151
check("Size", block.Size(), common.StorageSize(len(blockEnc)))
5252

5353
tx1 := NewTransaction(0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(10), big.NewInt(50000), big.NewInt(10), nil)
54-
tx1, _ = tx1.WithSignature(common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100"))
54+
tx1, _ = tx1.WithSignature(common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b11b"))
5555
check("len(Transactions)", len(block.Transactions()), 1)
5656
check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash())
5757

‎core/types/transaction.go‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,20 +318,22 @@ func (tx *Transaction) publicKey(homestead bool) ([]byte, error) {
318318
return pub, nil
319319
}
320320

321+
// WithSignature returns a new transaction with the given signature.
322+
// This signature needs to be formatted as described in the yellow paper (v+27).
321323
func (tx *Transaction) WithSignature(sig []byte) (*Transaction, error) {
322324
if len(sig) != 65 {
323325
panic(fmt.Sprintf("wrong size for signature: got %d, want 65", len(sig)))
324326
}
325327
cpy := &Transaction{data: tx.data}
326328
cpy.data.R = new(big.Int).SetBytes(sig[:32])
327329
cpy.data.S = new(big.Int).SetBytes(sig[32:64])
328-
cpy.data.V = sig[64] + 27
330+
cpy.data.V = sig[64]
329331
return cpy, nil
330332
}
331333

332334
func (tx *Transaction) SignECDSA(prv *ecdsa.PrivateKey) (*Transaction, error) {
333335
h := tx.SigHash()
334-
sig, err := crypto.Sign(h[:], prv)
336+
sig, err := crypto.SignEthereum(h[:], prv)
335337
if err != nil {
336338
return nil, err
337339
}

‎core/types/transaction_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ var (
4646
big.NewInt(1),
4747
common.FromHex("5544"),
4848
).WithSignature(
49-
common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a301"),
49+
common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a31c"),
5050
)
5151
)
5252

‎crypto/crypto.go‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ func Ripemd160(data []byte) []byte {
7878
return ripemd.Sum(nil)
7979
}
8080

81+
// Ecrecover returns the public key for the private key that was used to
82+
// calculate the signature.
83+
//
84+
// Note: secp256k1 expects the recover id to be either 0, 1. Ethereum
85+
// signatures have a recover id with an offset of 27. Callers must take
86+
// this into account and if "recovering" from an Ethereum signature adjust.
8187
func Ecrecover(hash, sig []byte) ([]byte, error) {
8288
return secp256k1.RecoverPubkey(hash, sig)
8389
}
@@ -192,17 +198,40 @@ func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
192198
return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
193199
}
194200

195-
func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
196-
if len(hash) != 32 {
197-
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
201+
// Sign calculates an ECDSA signature.
202+
// This function is susceptible to choosen plaintext attacks that can leak
203+
// information about the private key that is used for signing. Callers must
204+
// be aware that the given hash cannot be choosen by an adversery. Common
205+
// solution is to hash any input before calculating the signature.
206+
//
207+
// Note: the calculated signature is not Ethereum compliant. The yellow paper
208+
// dictates Ethereum singature to have a V value with and offset of 27 v in [27,28].
209+
// Use SignEthereum to get an Ethereum compliant signature.
210+
func Sign(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
211+
if len(data) != 32 {
212+
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(data))
198213
}
199214

200215
seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
201216
defer zeroBytes(seckey)
202-
sig, err = secp256k1.Sign(hash, seckey)
217+
sig, err = secp256k1.Sign(data, seckey)
203218
return
204219
}
205220

221+
// SignEthereum calculates an Ethereum ECDSA signature.
222+
// This function is susceptible to choosen plaintext attacks that can leak
223+
// information about the private key that is used for signing. Callers must
224+
// be aware that the given hash cannot be freely choosen by an adversery.
225+
// Common solution is to hash the message before calculating the signature.
226+
func SignEthereum(data []byte, prv *ecdsa.PrivateKey) ([]byte, error) {
227+
sig, err := Sign(data, prv)
228+
if err != nil {
229+
return nil, err
230+
}
231+
sig[64] += 27 // as described in the yellow paper
232+
return sig, err
233+
}
234+
206235
func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
207236
return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
208237
}

0 commit comments

Comments
 (0)