Go-ethereum 源码解析之 core/types/transaction_signing.go

Go-ethereum 源码解析之 core/types/transaction_signing.go

package types

import (
    "crypto/ecdsa"
    "errors"
    "fmt"
    "math/big"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/params"
)

var (
    ErrInvalidChainId = errors.New("invalid chain id for signer")
)

// sigCache is used to cache the derived sender and contains
// the signer used to derive it.
type sigCache struct {
    signer Signer
    from   common.Address
}

// MakeSigner returns a Signer based on the given chain config and block number.
func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
    var signer Signer
    switch {
    case config.IsEIP155(blockNumber):
        signer = NewEIP155Signer(config.ChainID)
    case config.IsHomestead(blockNumber):
        signer = HomesteadSigner{}
    default:
        signer = FrontierSigner{}
    }
    return signer
}

// SignTx signs the transaction using the given signer and private key
func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) {
    h := s.Hash(tx)
    sig, err := crypto.Sign(h[:], prv)
    if err != nil {
        return nil, err
    }
    return tx.WithSignature(s, sig)
}

// Sender returns the address derived from the signature (V, R, S) using secp256k1
// elliptic curve and an error if it failed deriving or upon an incorrect
// signature.
//
// Sender may cache the address, allowing it to be used regardless of
// signing method. The cache is invalidated if the cached signer does
// not match the signer used in the current call.
func Sender(signer Signer, tx *Transaction) (common.Address, error) {
    if sc := tx.from.Load(); sc != nil {
        sigCache := sc.(sigCache)
        // If the signer used to derive from in a previous
        // call is not the same as used current, invalidate
        // the cache.
        if sigCache.signer.Equal(signer) {
            return sigCache.from, nil
        }
    }

    addr, err := signer.Sender(tx)
    if err != nil {
        return common.Address{}, err
    }
    tx.from.Store(sigCache{signer: signer, from: addr})
    return addr, nil
}

// Signer encapsulates transaction signature handling. Note that this interface is not a
// stable API and may change at any time to accommodate new protocol rules.
type Signer interface {
    // Sender returns the sender address of the transaction.
    Sender(tx *Transaction) (common.Address, error)
    // SignatureValues returns the raw R, S, V values corresponding to the
    // given signature.
    SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error)
    // Hash returns the hash to be signed.
    Hash(tx *Transaction) common.Hash
    // Equal returns true if the given signer is the same as the receiver.
    Equal(Signer) bool
}

// EIP155Transaction implements Signer using the EIP155 rules.
type EIP155Signer struct {
    chainId, chainIdMul *big.Int
}

func NewEIP155Signer(chainId *big.Int) EIP155Signer {
    if chainId == nil {
        chainId = new(big.Int)
    }
    return EIP155Signer{
        chainId:    chainId,
        chainIdMul: new(big.Int).Mul(chainId, big.NewInt(2)),
    }
}

func (s EIP155Signer) Equal(s2 Signer) bool {
    eip155, ok := s2.(EIP155Signer)
    return ok && eip155.chainId.Cmp(s.chainId) == 0
}

var big8 = big.NewInt(8)

func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error) {
    if !tx.Protected() {
        return HomesteadSigner{}.Sender(tx)
    }
    if tx.ChainId().Cmp(s.chainId) != 0 {
        return common.Address{}, ErrInvalidChainId
    }
    V := new(big.Int).Sub(tx.data.V, s.chainIdMul)
    V.Sub(V, big8)
    return recoverPlain(s.Hash(tx), tx.data.R, tx.data.S, V, true)
}

// WithSignature returns a new transaction with the given signature. This signature
// needs to be in the [R || S || V] format where V is 0 or 1.
func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
    R, S, V, err = HomesteadSigner{}.SignatureValues(tx, sig)
    if err != nil {
        return nil, nil, nil, err
    }
    if s.chainId.Sign() != 0 {
        V = big.NewInt(int64(sig[64] + 35))
        V.Add(V, s.chainIdMul)
    }
    return R, S, V, nil
}

// Hash returns the hash to be signed by the sender.
// It does not uniquely identify the transaction.
func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
    return rlpHash([]interface{}{
        tx.data.AccountNonce,
        tx.data.Price,
        tx.data.GasLimit,
        tx.data.Recipient,
        tx.data.Amount,
        tx.data.Payload,
        s.chainId, uint(0), uint(0),
    })
}

// HomesteadTransaction implements TransactionInterface using the
// homestead rules.
type HomesteadSigner struct{ FrontierSigner }

func (s HomesteadSigner) Equal(s2 Signer) bool {
    _, ok := s2.(HomesteadSigner)
    return ok
}

// SignatureValues returns signature values. This signature
// needs to be in the [R || S || V] format where V is 0 or 1.
func (hs HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
    return hs.FrontierSigner.SignatureValues(tx, sig)
}

func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) {
    return recoverPlain(hs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, true)
}

type FrontierSigner struct{}

func (s FrontierSigner) Equal(s2 Signer) bool {
    _, ok := s2.(FrontierSigner)
    return ok
}

// SignatureValues returns signature values. This signature
// needs to be in the [R || S || V] format where V is 0 or 1.
func (fs FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
    if len(sig) != 65 {
        panic(fmt.Sprintf("wrong size for signature: got %d, want 65", len(sig)))
    }
    r = new(big.Int).SetBytes(sig[:32])
    s = new(big.Int).SetBytes(sig[32:64])
    v = new(big.Int).SetBytes([]byte{sig[64] + 27})
    return r, s, v, nil
}

// Hash returns the hash to be signed by the sender.
// It does not uniquely identify the transaction.
func (fs FrontierSigner) Hash(tx *Transaction) common.Hash {
    return rlpHash([]interface{}{
        tx.data.AccountNonce,
        tx.data.Price,
        tx.data.GasLimit,
        tx.data.Recipient,
        tx.data.Amount,
        tx.data.Payload,
    })
}

func (fs FrontierSigner) Sender(tx *Transaction) (common.Address, error) {
    return recoverPlain(fs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, false)
}

func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) {
    if Vb.BitLen() > 8 {
        return common.Address{}, ErrInvalidSig
    }
    V := byte(Vb.Uint64() - 27)
    if !crypto.ValidateSignatureValues(V, R, S, homestead) {
        return common.Address{}, ErrInvalidSig
    }
    // encode the snature in uncompressed format
    r, s := R.Bytes(), S.Bytes()
    sig := make([]byte, 65)
    copy(sig[32-len(r):32], r)
    copy(sig[64-len(s):64], s)
    sig[64] = V
    // recover the public key from the snature
    pub, err := crypto.Ecrecover(sighash[:], sig)
    if err != nil {
        return common.Address{}, err
    }
    if len(pub) == 0 || pub[0] != 4 {
        return common.Address{}, errors.New("invalid public key")
    }
    var addr common.Address
    copy(addr[:], crypto.Keccak256(pub[1:])[12:])
    return addr, nil
}

// deriveChainId derives the chain id from the given v parameter
func deriveChainId(v *big.Int) *big.Int {
    if v.BitLen() <= 64 {
        v := v.Uint64()
        if v == 27 || v == 28 {
            return new(big.Int)
        }
        return new(big.Int).SetUint64((v - 35) / 2)
    }
    v = new(big.Int).Sub(v, big.NewInt(35))
    return v.Div(v, big.NewInt(2))
}

Appendix A. 总体批注

文件 core/types/transaction_signing.go 主要定义了接口 Singer 及三个具体的实现 EIP155Signer、HomesteadSigner、FrontierSigner。

实现了几个辅助函数用于处理事务签名:

  • 函数 MakeSigner() 基于给定的链配置和区块编号返回签名者。
  • 函数 SignTx() 使用给定的签名者和私钥来签名事务,并返回签名后的新事务。
  • 函数 Sender() 返回给定签名者和事务的签名者地址。
  • 函数 recoverPlain() 根据事务的哈希和签名信息的 R, S,V 值最终计算出发送者地址。
  • 函数 deriveChainId() 从给定的参数 v 中推导出 chain id。

Appendix B. 详细批注

var

  • ErrInvalidChainId: 表示 chain id 对于 signer 来说无效的 error 值。

type sigCache struct

sigCache 用于缓存被推导出的发送者地址,同时包含了用于推导的签名者。

signer Signer:         签名者
from   common.Address: 发送者地址

func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer

函数 MakeSigner() 基于给定的链配置和区块编号返回签名者。

主要实现的具体细节如下:

  • 如果 blockNumber 为 EIP155 协议,则返回内置签名者 EIP155Signer。
  • 如果 blockNumber 为 homestead 协议,则返回内置签名者 HomesteadSigner。
  • 否则返回内置签名者 FrontierSigner。

func SignTx(tx *Transaction, s Signer, prv ecdsa.PrivateKey) (Transaction, error)

函数 SignTx() 使用给定的签名者和私钥来签名事务,并返回签名后的新事务。

主要实现的具体细节如下:

  • 签名者先计算事务的哈希值。这里应该是对于同一事务,不同的签名者计算哈希的规则不同。
  • 通过函数 crypto.Sign() 返回私钥对于事务哈希的 ECDSA 签名,具体签名信息包括 R, S, V。
  • 调用方法 tx.WithSignature() 返回将签名者和 ECDSA 签名应用于事务之后带签名信息的新事务。

func Sender(signer Signer, tx *Transaction) (common.Address, error)

函数 Sender() 返回给定签名者和事务的签名者地址。根据事务中的签名信息 (V, R, S) 使用 secp256k1 eliptic curve 算法。

Transaction 中有签名者相关信息的缓存,具体为 Transaction 中的字段 from 为数据结构 sigCache。

主要实现的具体细节如下:

  • 先获取 tx.from 并恢复为 sigCache 类型,如果 sigCache.signer 和参数 signer 相等,则返回 sigCache.from。
  • 否则,调用 singer.Sender(tx) 返回签名者地址,并构建签名信息 sigCache 缓存到 tx.from 字段。

type Signer interface

接口 Singer 封装了事务的签名处理。注意,这个接口不是稳定的 API,并且随时有可能被修改以适应新的协议规则。

  1. Sender(tx *Transaction) (common.Address, error)
    方法 Sender() 返回事务的发送者地址。

  2. SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error)
    方法 SignatureValues() 返回事务对于给定签名的原始 R, S, V 值。

  3. Hash(tx *Transaction) common.Hash
    方法 Hash() 返回给定事务的哈希,以便后续的签名。

  4. Equal(Signer) bool
    方法 Equal() 在给定的签名者与接收者相同时返回真。

type EIP155Signer struct

EIP155Signer 采用 EIP155 规则实现了接口 Singer。

  • chainId *big.Int
  • chainIdMul *big.Int
  1. func NewEIP155Signer(chainId *big.Int) EIP155Signer
    方法 NewEIP155Signer() 创建一个新的 EIP155Signer

  2. func (s EIP155Signer) Equal(s2 Signer) bool
    方法 Equal() 实现了接口 Singer。方法 Equal() 在给定的签名者与接收者相同时返回真。

主要实现的具体细节如下:

  • 判断Singer s2 是否为 EIP155Signer。
  • 比较 EIP155Signer 中的字段 chainId 是否一致。
  1. func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error)
    方法 Sender() 实现了接口 Singer。方法 Sender() 返回事务的发送者地址。

主要实现的具体细节如下:

  • 参考具体的算法。
  1. func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error)
    方法 SignatureValues() 实现了接口 Singer。方法 SignatureValues() 返回事务对于给定签名的原始 R, S, V 值。

主要实现的具体细节如下:

  • 参考具体的算法。
  1. func (s EIP155Signer) Hash(tx *Transaction) common.Hash
    方法 Hash() 实现了接口 Singer。方法 Hash() 返回事务的哈希。这里的哈希并不能唯一标识事务。

主要实现的具体细节如下:

  • 调用函数 rlpHash()。

type HomesteadSigner struct

HomesteadSigner 采用 homestead 规则实现了接口 Singer。HomesteadSigner 继承了 FrontierSigner。

  1. func (s HomesteadSigner) Equal(s2 Signer) bool
    方法 Equal() 实现了接口 Singer。方法 Equal() 在给定的签名者与接收者相同时返回真。

主要实现的具体细节如下:

  • 判断Singer s2 是否为 HomesteadSigner。
  1. func (s HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error)
    方法 SignatureValues() 实现了接口 Singer。方法 SignatureValues() 返回事务对于给定签名的原始 R, S, V 值。

主要实现的具体细节如下:

  • 转发给父类的方法 FrontierSigner.SignatureValues()。
  1. func (s HomesteadSigner) Sender(tx *Transaction) (common.Address, error)
    方法 Sender() 实现了接口 Singer。方法 Sender() 返回事务的发送者地址。

主要实现的具体细节如下:

  • 调用方法 recoverPlain()。

type FrontierSigner struct

FrontierSigner 采用自己的规则实现了接口 Singer。

  1. func (s FrontierSigner) Equal(s2 Signer) bool
    方法 Equal() 实现了接口 Singer。方法 Equal() 在给定的签名者与接收者相同时返回真。

主要实现的具体细节如下:

  • 判断Singer s2 是否为 FrontierSigner。
  1. func (s FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error)
    方法 SignatureValues() 实现了接口 Singer。方法 SignatureValues() 返回事务对于给定签名的原始 R, S, V 值。

主要实现的具体细节如下:

  • 先判定签名 sig 的长度是否为 65 字节。
  • 参考具体的算法计算 r, s, v。
  1. func (s FrontierSigner) Hash(tx *Transaction) common.Hash
    方法 Hash() 实现了接口 Singer。方法 Hash() 返回事务的哈希。这里的哈希并不能唯一标识事务。

主要实现的具体细节如下:

  • 调用函数 rlpHash()。
  1. func (s FrontierSigner) Sender(tx *Transaction) (common.Address, error)
    方法 Sender() 实现了接口 Singer。方法 Sender() 返回事务的发送者地址。

主要实现的具体细节如下:

  • 调用方法 recoverPlain()。

func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error)

函数 recoverPlain() 根据事务的哈希和签名信息的 R, S,V 值最终计算出发送者地址。

主要实现的具体细节如下:

  • 参考具体的算法。

func deriveChainId(v *big.Int) *big.Int

函数 deriveChainId() 从给定的参数 v 中推导出 chain id。

主要实现的具体细节如下:

  • 参考具体的算法。

Reference

  1. https://github.com/ethereum/go-ethereum/blob/master/core/types/transaction_signing.go

Contributor

  1. Windstamp, https://github.com/windstamp
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容