github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/accounts/accounts.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package accounts implements high level Ethereum account management.
    18  package accounts
    19  
    20  import (
    21  	"fmt"
    22  	"math/big"
    23  
    24  	"github.com/aidoskuneen/adk-node"
    25  	"github.com/aidoskuneen/adk-node/common"
    26  	"github.com/aidoskuneen/adk-node/core/types"
    27  	"github.com/aidoskuneen/adk-node/event"
    28  	"golang.org/x/crypto/sha3"
    29  )
    30  
    31  // Account represents an Ethereum account located at a specific location defined
    32  // by the optional URL field.
    33  type Account struct {
    34  	Address common.Address `json:"address"` // Ethereum account address derived from the key
    35  	URL     URL            `json:"url"`     // Optional resource locator within a backend
    36  }
    37  
    38  const (
    39  	MimetypeDataWithValidator = "data/validator"
    40  	MimetypeTypedData         = "data/typed"
    41  	MimetypeClique            = "application/x-clique-header"
    42  	MimetypeTextPlain         = "text/plain"
    43  )
    44  
    45  // Wallet represents a software or hardware wallet that might contain one or more
    46  // accounts (derived from the same seed).
    47  type Wallet interface {
    48  	// URL retrieves the canonical path under which this wallet is reachable. It is
    49  	// user by upper layers to define a sorting order over all wallets from multiple
    50  	// backends.
    51  	URL() URL
    52  
    53  	// Status returns a textual status to aid the user in the current state of the
    54  	// wallet. It also returns an error indicating any failure the wallet might have
    55  	// encountered.
    56  	Status() (string, error)
    57  
    58  	// Open initializes access to a wallet instance. It is not meant to unlock or
    59  	// decrypt account keys, rather simply to establish a connection to hardware
    60  	// wallets and/or to access derivation seeds.
    61  	//
    62  	// The passphrase parameter may or may not be used by the implementation of a
    63  	// particular wallet instance. The reason there is no passwordless open method
    64  	// is to strive towards a uniform wallet handling, oblivious to the different
    65  	// backend providers.
    66  	//
    67  	// Please note, if you open a wallet, you must close it to release any allocated
    68  	// resources (especially important when working with hardware wallets).
    69  	Open(passphrase string) error
    70  
    71  	// Close releases any resources held by an open wallet instance.
    72  	Close() error
    73  
    74  	// Accounts retrieves the list of signing accounts the wallet is currently aware
    75  	// of. For hierarchical deterministic wallets, the list will not be exhaustive,
    76  	// rather only contain the accounts explicitly pinned during account derivation.
    77  	Accounts() []Account
    78  
    79  	// Contains returns whether an account is part of this particular wallet or not.
    80  	Contains(account Account) bool
    81  
    82  	// Derive attempts to explicitly derive a hierarchical deterministic account at
    83  	// the specified derivation path. If requested, the derived account will be added
    84  	// to the wallet's tracked account list.
    85  	Derive(path DerivationPath, pin bool) (Account, error)
    86  
    87  	// SelfDerive sets a base account derivation path from which the wallet attempts
    88  	// to discover non zero accounts and automatically add them to list of tracked
    89  	// accounts.
    90  	//
    91  	// Note, self derivation will increment the last component of the specified path
    92  	// opposed to decending into a child path to allow discovering accounts starting
    93  	// from non zero components.
    94  	//
    95  	// Some hardware wallets switched derivation paths through their evolution, so
    96  	// this method supports providing multiple bases to discover old user accounts
    97  	// too. Only the last base will be used to derive the next empty account.
    98  	//
    99  	// You can disable automatic account discovery by calling SelfDerive with a nil
   100  	// chain state reader.
   101  	SelfDerive(bases []DerivationPath, chain ethereum.ChainStateReader)
   102  
   103  	// SignData requests the wallet to sign the hash of the given data
   104  	// It looks up the account specified either solely via its address contained within,
   105  	// or optionally with the aid of any location metadata from the embedded URL field.
   106  	//
   107  	// If the wallet requires additional authentication to sign the request (e.g.
   108  	// a password to decrypt the account, or a PIN code o verify the transaction),
   109  	// an AuthNeededError instance will be returned, containing infos for the user
   110  	// about which fields or actions are needed. The user may retry by providing
   111  	// the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
   112  	// the account in a keystore).
   113  	SignData(account Account, mimeType string, data []byte) ([]byte, error)
   114  
   115  	// SignDataWithPassphrase is identical to SignData, but also takes a password
   116  	// NOTE: there's a chance that an erroneous call might mistake the two strings, and
   117  	// supply password in the mimetype field, or vice versa. Thus, an implementation
   118  	// should never echo the mimetype or return the mimetype in the error-response
   119  	SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
   120  
   121  	// SignText requests the wallet to sign the hash of a given piece of data, prefixed
   122  	// by the Ethereum prefix scheme
   123  	// It looks up the account specified either solely via its address contained within,
   124  	// or optionally with the aid of any location metadata from the embedded URL field.
   125  	//
   126  	// If the wallet requires additional authentication to sign the request (e.g.
   127  	// a password to decrypt the account, or a PIN code o verify the transaction),
   128  	// an AuthNeededError instance will be returned, containing infos for the user
   129  	// about which fields or actions are needed. The user may retry by providing
   130  	// the needed details via SignTextWithPassphrase, or by other means (e.g. unlock
   131  	// the account in a keystore).
   132  	//
   133  	// This method should return the signature in 'canonical' format, with v 0 or 1
   134  	SignText(account Account, text []byte) ([]byte, error)
   135  
   136  	// SignTextWithPassphrase is identical to Signtext, but also takes a password
   137  	SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
   138  
   139  	// SignTx requests the wallet to sign the given transaction.
   140  	//
   141  	// It looks up the account specified either solely via its address contained within,
   142  	// or optionally with the aid of any location metadata from the embedded URL field.
   143  	//
   144  	// If the wallet requires additional authentication to sign the request (e.g.
   145  	// a password to decrypt the account, or a PIN code to verify the transaction),
   146  	// an AuthNeededError instance will be returned, containing infos for the user
   147  	// about which fields or actions are needed. The user may retry by providing
   148  	// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
   149  	// the account in a keystore).
   150  	SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
   151  
   152  	// SignTxWithPassphrase is identical to SignTx, but also takes a password
   153  	SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
   154  }
   155  
   156  // Backend is a "wallet provider" that may contain a batch of accounts they can
   157  // sign transactions with and upon request, do so.
   158  type Backend interface {
   159  	// Wallets retrieves the list of wallets the backend is currently aware of.
   160  	//
   161  	// The returned wallets are not opened by default. For software HD wallets this
   162  	// means that no base seeds are decrypted, and for hardware wallets that no actual
   163  	// connection is established.
   164  	//
   165  	// The resulting wallet list will be sorted alphabetically based on its internal
   166  	// URL assigned by the backend. Since wallets (especially hardware) may come and
   167  	// go, the same wallet might appear at a different positions in the list during
   168  	// subsequent retrievals.
   169  	Wallets() []Wallet
   170  
   171  	// Subscribe creates an async subscription to receive notifications when the
   172  	// backend detects the arrival or departure of a wallet.
   173  	Subscribe(sink chan<- WalletEvent) event.Subscription
   174  }
   175  
   176  // TextHash is a helper function that calculates a hash for the given message that can be
   177  // safely used to calculate a signature from.
   178  //
   179  // The hash is calulcated as
   180  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
   181  //
   182  // This gives context to the signed message and prevents signing of transactions.
   183  func TextHash(data []byte) []byte {
   184  	hash, _ := TextAndHash(data)
   185  	return hash
   186  }
   187  
   188  // TextAndHash is a helper function that calculates a hash for the given message that can be
   189  // safely used to calculate a signature from.
   190  //
   191  // The hash is calulcated as
   192  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
   193  //
   194  // This gives context to the signed message and prevents signing of transactions.
   195  func TextAndHash(data []byte) ([]byte, string) {
   196  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data))
   197  	hasher := sha3.NewLegacyKeccak256()
   198  	hasher.Write([]byte(msg))
   199  	return hasher.Sum(nil), msg
   200  }
   201  
   202  // WalletEventType represents the different event types that can be fired by
   203  // the wallet subscription subsystem.
   204  type WalletEventType int
   205  
   206  const (
   207  	// WalletArrived is fired when a new wallet is detected either via USB or via
   208  	// a filesystem event in the keystore.
   209  	WalletArrived WalletEventType = iota
   210  
   211  	// WalletOpened is fired when a wallet is successfully opened with the purpose
   212  	// of starting any background processes such as automatic key derivation.
   213  	WalletOpened
   214  
   215  	// WalletDropped
   216  	WalletDropped
   217  )
   218  
   219  // WalletEvent is an event fired by an account backend when a wallet arrival or
   220  // departure is detected.
   221  type WalletEvent struct {
   222  	Wallet Wallet          // Wallet instance arrived or departed
   223  	Kind   WalletEventType // Event type that happened in the system
   224  }