以太坊源码分析之五帐户和钱包

以太坊和比特币在管理用户帐户上有很大不同,比特币使用的是UTXO模型,没有传统意义上的帐户一说,而以太坊使用了帐户。
如果有以太坊交易或者私链搭建的经验,就很清楚知道在交易的时候只要向一个地址发送以太币就可以了,类似:
eth.sendTransaction({
from: "0xf8a4909ce93a9d876b8f787e4771d87d6899d879", 
to: "0x72b92aebbd254f808cef0afbf5c96e7ae681cfda", value: web3.toWei(100, "ether"
)})
这是web3j的转帐方式,所以说应该说只要有一个合法的以太坊的地址就能够在以太坊区块链上进行交易。也就是说,地址才是交易的最基本的单位。
但是地址太长了,又没有规律,很容易忘记或者说丢失,所以就需要管理它的一个基本数据结构,那就是帐户Account。而一个人很可能会有多个帐户,所以就需要钱包来管理它(是不是类似于真实的世界,你多个银行户头号码,对应着多个银行卡,然后银行卡放到钱包中管理),然后为了管理多个钱包,又需要有一个皮包Manager。
与现实世界不同的是,钱包有软硬之分,其实只是相对而言,普通钱包是存放在电脑上的。而硬钱包是为了安全放到USB硬件设备中去的,这个类似于银行的U盾。而在实际的场景下,几乎目前还没有看到真正有几个人用。可能都是持币大户在用吧,一般人看不到。
另外还有一个需要注意的是,这个模块中还提供了一个后台钱包provider类(可以叫提供器或者供应者),用来动态提供一批帐号,类似于比特币的地址生成器。
虽然golang没有类这个说法,但是毕竟还是面向对象,所以提供一个简单的类图来对照一下:
 
具体的类代码和工程所在文件如下:


Accouts.go
// Account represents an Ethereum account located at a specific location defined
// by the optional URL field.
type Account struct {
Address common.Address `json:"address"` // Ethereum account address derived from the key
    //URL可选字段
URL     URL            `json:"url"`     // Optional resource locator within a backend
}


// Wallet represents a software or hardware wallet that might contain one or more
// accounts (derived from the same seed).
type Wallet interface {
// URL retrieves the canonical path under which this wallet is reachable. It is
// user by upper layers to define a sorting order over all wallets from multiple
// backends.
//获得钱包的规范路径,供上层使用。为多个后端钱包排序用。
URL() URL


// Status returns a textual status to aid the user in the current state of the
// wallet. It also returns an error indicating any failure the wallet might have
// encountered.
Status() (string, error)


// Open initializes access to a wallet instance. It is not meant to unlock or
// decrypt account keys, rather simply to establish a connection to hardware
// wallets and/or to access derivation seeds.
//打开并不意味着解锁或者解密,这里只是打开钱包,银行卡还得要密码
// The passphrase parameter may or may not be used by the implementation of a
// particular wallet instance. The reason there is no passwordless open method
// is to strive towards a uniform wallet handling, oblivious to the different
// backend providers.
//记住一定用完要关掉它
// Please note, if you open a wallet, you must close it to release any allocated
// resources (especially important when working with hardware wallets).
Open(passphrase string) error


// Close releases any resources held by an open wallet instance.
Close() error


// Accounts retrieves the list of signing accounts the wallet is currently aware
// of. For hierarchical deterministic wallets, the list will not be exhaustive,
// rather only contain the accounts explicitly pinned during account derivation.
    //注意确定分层钱包,不会列出所有,只列出明确的帐户
Accounts() []Account


// Contains returns whether an account is part of this particular wallet or not.
Contains(account Account) bool


// Derive attempts to explicitly derive a hierarchical deterministic account at
// the specified derivation path. If requested, the derived account will be added
// to the wallet's tracked account list.
    //派生路径派生分层确定帐户,如果PINT为真,则将帐户添加到上面的追踪列表中
Derive(path DerivationPath, pin bool) (Account, error)


// SelfDerive sets a base account derivation path from which the wallet attempts
// to discover non zero accounts and automatically add them to list of tracked
// accounts.
//设置一个基本帐户的导出路径,并从中寻找非零帐户,并自动将其添加到追踪列表
// Note, self derivaton will increment the last component of the specified path
// opposed to decending into a child path to allow discovering accounts starting
// from non zero components.
//不包含递归,只找当前
// You can disable automatic account discovery by calling SelfDerive with a nil
// chain state reader.可以指定禁止
SelfDerive(base DerivationPath, chain ethereum.ChainStateReader)


// SignHash requests the wallet to sign the given hash.
//对传入的HASH进行签名
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
/通过account来查找帐户
// If the wallet requires additional authentication to sign the request (e.g.
// a password to decrypt the account, or a PIN code o verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
    //如果需要额外签名,比如需要密码解锁帐户或者一个PIN代码来通信交易,会返回一//个授权错误的信息
SignHash(account Account, hash []byte) ([]byte, error)


// SignTx requests the wallet to sign the given transaction.
//对交易进行签名
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
//
// If the wallet requires additional authentication to sign the request (e.g.
// a password to decrypt the account, or a PIN code o verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)


    下面两个类似,用指定的Passphrase签名
// SignHashWithPassphrase requests the wallet to sign the given hash with the
// given passphrase as extra authentication information.
//
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
SignHashWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)


// SignTxWithPassphrase requests the wallet to sign the given transaction, with the
// given passphrase as extra authentication information.
//
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
}


// Backend is a "wallet provider" that may contain a batch of accounts they can
// sign transactions with and upon request, do so.
type Backend interface {
// Wallets retrieves the list of wallets the backend is currently aware of.
//
// The returned wallets are not opened by default. For software HD wallets this
// means that no base seeds are decrypted, and for hardware wallets that no actual
// connection is established.
//
// The resulting wallet list will be sorted alphabetically based on its internal
// URL assigned by the backend. Since wallets (especially hardware) may come and
// go, the same wallet might appear at a different positions in the list during
// subsequent retrievals.
Wallets() []Wallet


// Subscribe creates an async subscription to receive notifications when the
// backend detects the arrival or departure of a wallet.
Subscribe(sink chan<- WalletEvent) event.Subscription
}


// WalletEventType represents the different event types that can be fired by
// the wallet subscription subsystem.
type WalletEventType int


const (
// WalletArrived is fired when a new wallet is detected either via USB or via
// a filesystem event in the keystore.
WalletArrived WalletEventType = iota


// WalletOpened is fired when a wallet is successfully opened with the purpose
// of starting any background processes such as automatic key derivation.
WalletOpened


// WalletDropped
WalletDropped
)


// WalletEvent is an event fired by an account backend when a wallet arrival or
// departure is detected.
type WalletEvent struct {
Wallet Wallet          // Wallet instance arrived or departed
Kind   WalletEventType // Event type that happened in the system
}
Manager.go
// Manager is an overarching account manager that can communicate with various
// backends for signing transactions.
type Manager struct {
    //当前注册的backends
backends map[reflect.Type][]Backend // Index of backends currently registered
//全部的更新订阅者
updaters []event.Subscription       // Wallet update subscriptions for all backends
// 更新事件
updates  chan WalletEvent           // Subscription sink for backend wallet changes
wallets  []Wallet                   // Cache of all wallets from all registered backends
//钱包事件的到达和离开通知动作
feed event.Feed // Wallet feed notifying of arrivals/departures


quit chan chan error
lock sync.RWMutex
}
在前面创建节点的时候儿有一个这个动作:
// New creates a new P2P node, ready for protocol registration.
func New(conf *Config) (*Node, error) {
……
// Ensure that the AccountManager method works before the node has started.
// We rely on this in cmd/geth.
am, ephemeralKeystore, err := makeAccountManager(conf)
……
}
这个函数会调用:
// NewManager creates a generic account manager to sign transaction via various
// supported backends.
func NewManager(backends ...Backend) *Manager {
// Retrieve the initial list of wallets from the backends and sort by URL
var wallets []Wallet
for _, backend := range backends {
wallets = merge(wallets, backend.Wallets()...)
}
// Subscribe to wallet notifications from all backends
updates := make(chan WalletEvent, 4*len(backends))


subs := make([]event.Subscription, len(backends))
for i, backend := range backends {
subs[i] = backend.Subscribe(updates)
}
// Assemble the account manager and return
am := &Manager{
backends: make(map[reflect.Type][]Backend),
updaters: subs,
updates:  updates,
wallets:  wallets,
quit:     make(chan chan error),
}
for _, backend := range backends {
kind := reflect.TypeOf(backend)
am.backends[kind] = append(am.backends[kind], backend)
}
go am.update()


return am
}
就来到了帐户的创建过程中。前面提到过事件的订阅和更新:
// Subscribe creates an async subscription to receive notifications when the
// manager detects the arrival or departure of a wallet from any of its backends.
func (am *Manager) Subscribe(sink chan<- WalletEvent) event.Subscription {
return am.feed.Subscribe(sink)
}
// update is the wallet event loop listening for notifications from the backends
// and updating the cache of wallets.
func (am *Manager) update() {
// Close all subscriptions when the manager terminates
defer func() {
am.lock.Lock()
for _, sub := range am.updaters {
sub.Unsubscribe()
}
am.updaters = nil
am.lock.Unlock()
}()


// Loop until termination
for {
select {
case event := <-am.updates:
// Wallet event arrived, update local cache
am.lock.Lock()
switch event.Kind {
case WalletArrived:
am.wallets = merge(am.wallets, event.Wallet)
case WalletDropped:
am.wallets = drop(am.wallets, event.Wallet)
}
am.lock.Unlock()


// Notify any listeners of the event
am.feed.Send(event)


case errc := <-am.quit:
// Manager terminating, return
errc <- nil
return
}
}
}
这个函数中实现了一个goroutine,循环监听backend触发的更新信息,然后转发到feed,前面提到过。
以太坊的各个客户端的Manger对象互相订阅Wallet更新事件,保持帐户的一致性。而Manager实现了Backend的接口中的Subscribe函数。
基本理清了钱包帐户的互相关系和实现步骤,来看一下两类钱包,首先看本地钱包keystore:
// KeyStore manages a key storage directory on disk.
type KeyStore struct {
storage  keyStore                     // Storage backend, might be cleartext or encrypted
cache    *accountCache                // In-memory account cache over the filesystem storage
changes  chan struct{}                // Channel receiving change notifications from the cache
unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)


wallets     []accounts.Wallet       // Wallet wrappers around the individual key files
updateFeed  event.Feed              // Event feed to notify wallet additions/removals
updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
updating    bool                    // Whether the event notification loop is running


mu sync.RWMutex
}
看上面的英文注释,用来管理KEY的本地存储的。看一 下它的类图:
 


存续的目的不外乎是增加访问速度,没啥可分析的。主要是前面提到过的keyStorePassphrase{}:<keyStore>接口的实现类,它实现了以Web3 Secret Storage加密方法为公钥密钥信息进行加密管理。
本地文件的存储都是JSON格式的,这样在使用的时候儿就方便很多。
再有一个就是KEY这个结构体:
type Key struct {
Id uuid.UUID // Version 4 "random" for unique id not derived from key data
// to simplify lookups we also store the address
Address common.Address
// we only store privkey as pubkey/address can be derived from it
// privkey in this struct is always in plaintext
PrivateKey *ecdsa.PrivateKey
}
最后一个成员变量,私钥,但其中有一个PublicKey的成员变量和一个Address成员类型变量,形成映射对。不需要来回经常切换。以太坊的钱包在创建密码时正是对应着passphrase。它的示意图如下:
 
Key是封装到类图中unlocked 这个对象中。它提供了一个时限操作函数,TimedUnlock,这个函数会在时限到达后将PrivateKey销毁同时将unlocked对象从KeyStore对象中删除。
然后再分析一下硬钱包:
// wallet represents the common functionality shared by all USB hardware
// wallets to prevent reimplementing the same complex maintenance mechanisms
// for different vendors.
type wallet struct {
hub    *Hub          // USB hub scanning
driver driver        // Hardware implementation of the low level device operations
url    *accounts.URL // Textual URL uniquely identifying this wallet


info   hid.DeviceInfo // Known USB device infos about the wallet
device *hid.Device    // USB device advertising itself as a hardware wallet


accounts []accounts.Account                         // List of derive accounts pinned on the hardware wallet
paths    map[common.Address]accounts.DerivationPath // Known derivation paths for signing operations


deriveNextPath accounts.DerivationPath   // Next derivation path for account auto-discovery
deriveNextAddr common.Address            // Next derived account address for auto-discovery
deriveChain    ethereum.ChainStateReader // Blockchain state reader to discover used account with
deriveReq      chan chan struct{}        // Channel to request a self-derivation on
deriveQuit     chan chan error           // Channel to terminate the self-deriver with


healthQuit chan chan error


// Locking a hardware wallet is a bit special. Since hardware devices are lower
// performing, any communication with them might take a non negligible amount of
// time. Worse still, waiting for user confirmation can take arbitrarily long,
// but exclusive communication must be upheld during. Locking the entire wallet
// in the mean time however would stall any parts of the system that don't want
// to communicate, just read some state (e.g. list the accounts).
//
// As such, a hardware wallet needs two locks to function correctly. A state
// lock can be used to protect the wallet's software-side internal state, which
// must not be held exlusively during hardware communication. A communication
// lock can be used to achieve exclusive access to the device itself, this one
// however should allow "skipping" waiting for operations that might want to
// use the device, but can live without too (e.g. account self-derivation).
//
// Since we have two locks, it's important to know how to properly use them:
//   - Communication requires the `device` to not change, so obtaining the
//     commsLock should be done after having a stateLock.
//   - Communication must not disable read access to the wallet state, so it
//     must only ever hold a *read* lock to stateLock.
commsLock chan struct{} // Mutex (buf=1) for the USB comms without keeping the state locked
stateLock sync.RWMutex  // Protects read and write access to the wallet struct fields


log log.Logger // Contextual logger to tag the base with its id
}
类图如下:
 
说一下下面的两个驱动,Ledger Nano S是法国公司,私有固件,成立的 时间还不太长。Trezor是捷克团队的产品,开源固件,安全性照说会好一些,并且公司成立时间也久一些,更经受过考验。
需要注意的是目前以太坊的代码硬件实现钱包的数字签名部分还没有完全搞定。只提供对交易进行原生的数字签名,其它暂未搞定。可能得看后续版本。
咋说呢,就一两个以太坊还是省省吧,这个硬件钱包还一百欧呢。

具体到加密算法,比如像比特币那样的具体的说明还不太有把握,等吃透了后,在后面再补专门的章节来分析。

提两个小问题,供大家分析讨论:

使用帐户而不使用UTXO自然会带一个比较麻烦的问题,也就是双花。传统的中心化的体系解决这个问题没有什么难点,UTXO也很好解决。
以太坊是怎么处理的呢?智能合约帐户和外部拥有帐户又有什么不同呢?

今天还算顺利,下周进行交易的分析。

猜你喜欢

转载自blog.csdn.net/fpcc/article/details/80953935
今日推荐