forked from NebulousLabs/Sia
/
wallet.go
374 lines (315 loc) · 16 KB
/
wallet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package modules
import (
"bytes"
"errors"
"github.com/NebulousLabs/entropy-mnemonics"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/types"
)
const (
WalletDir = "wallet"
SeedChecksumSize = 6
PublicKeysPerSeed = 2500
WalletSeedPreloadDepth = 25
)
var (
ErrBadEncryptionKey = errors.New("provided encryption key is incorrect")
ErrLowBalance = errors.New("insufficient balance")
ErrPotentialDoubleSpend = errors.New("wallet has coins spent in unconfirmed transactions - not enough remaining coins to complete transaction")
ErrLockedWallet = errors.New("wallet must be unlocked before it can be used")
)
type (
// AddressSeed is cryptographic entropy that is used to derive spendable
// wallet addresses.
Seed [crypto.EntropySize]byte
// WalletTransactionID is a unique identifier for a wallet transaction.
WalletTransactionID crypto.Hash
// A WalletAddress is an address. A struct is used so that it can be
// expanded in the future to include items such as balances.
WalletAddress struct {
Address types.UnlockHash `json:"address"`
}
// A ProcessedInput represents funding to a transaction. The input is
// coming from an address and going to the outputs. The fund types are
// 'SiacoinInput', 'SiafundInput'.
ProcessedInput struct {
FundType types.Specifier `json:"fundtype"`
WalletAddress bool `json:"walletaddress"`
RelatedAddress types.UnlockHash `json:"relatedaddress"`
Value types.Currency `json:"value"`
}
// A ProcessedOutput is a siacoin output that appears in a transaction.
// Some outputs mature immediately, some are delayed, and some may never
// mature at all (in the event of storage proofs).
//
// Fund type can either be 'SiacoinOutput', 'SiafundOutput', 'ClaimOutput',
// 'MinerPayout', or 'MinerFee'. All outputs except the miner fee create
// outputs accessible to an address. Miner fees are not spendable, and
// instead contribute to the block subsidy.
//
// MaturityHeight indicates at what block height the output becomes
// available. SiacoinInputs and SiafundInputs become available immediately.
// ClaimInputs and MinerPayouts become available after 144 confirmations.
ProcessedOutput struct {
FundType types.Specifier `json:"fundtype"`
MaturityHeight types.BlockHeight `json:"maturityheight"`
WalletAddress bool `json:"walletaddress"`
RelatedAddress types.UnlockHash `json:"relatedaddress"`
Value types.Currency `json:"value"`
}
// A processed transaction is a transaction that has been processed into
// explicit inputs and outputs and tagged with some header data such as
// confirmation height + timestamp.
//
// Because of the block subsidy, a block is considered as a transaction.
// Since there is technically no transaction id for the block subsidy, the
// block id is used instead.
ProcessedTransaction struct {
Transaction types.Transaction `json:"transaction"`
TransactionID types.TransactionID `json:"transactionid"`
ConfirmationHeight types.BlockHeight `json:"confirmationheight"`
ConfirmationTimestamp types.Timestamp `json:"confirmationtimestamp"`
Inputs []ProcessedInput `json:"inputs"`
Outputs []ProcessedOutput `json:"outputs"`
}
// TransactionBuilder is used to construct custom transactions. A transaction
// builder is intialized via 'RegisterTransaction' and then can be modified by
// adding funds or other fields. The transaction is completed by calling
// 'Sign', which will sign all inputs added via the 'FundSiacoins' or
// 'FundSiafunds' call. All modifications are additive.
//
// Parents of the transaction are kept in the transaction builder. A parent is
// any unconfirmed transaction that is required for the child to be valid.
//
// Transaction builders are not thread safe.
TransactionBuilder interface {
// FundSiacoins will add a siacoin input of exaclty 'amount' to the
// transaction. A parent transaction may be needed to achieve an input
// with the correct value. The siacoin input will not be signed until
// 'Sign' is called on the transaction builder. The expectation is that
// the transaction will be completed and broadcast within a few hours.
// Longer risks double-spends, as the wallet will assume that the
// transaction failed.
FundSiacoins(amount types.Currency) error
// FundSiafunds will add a siafund input of exaclty 'amount' to the
// transaction. A parent transaction may be needed to achieve an input
// with the correct value. The siafund input will not be signed until
// 'Sign' is called on the transaction builder. Any siacoins that are
// released by spending the siafund outputs will be sent to another
// address owned by the wallet. The expectation is that the transaction
// will be completed and broadcast within a few hours. Longer risks
// double-spends, because the wallet will assume the transcation
// failed.
FundSiafunds(amount types.Currency) error
// AddMinerFee adds a miner fee to the transaction, returning the index
// of the miner fee within the transaction.
AddMinerFee(fee types.Currency) uint64
// AddSiacoinInput adds a siacoin input to the transaction, returning
// the index of the siacoin input within the transaction. When 'Sign'
// gets called, this input will be left unsigned.
AddSiacoinInput(types.SiacoinInput) uint64
// AddSiacoinOutput adds a siacoin output to the transaction, returning
// the index of the siacoin output within the transaction.
AddSiacoinOutput(types.SiacoinOutput) uint64
// AddFileContract adds a file contract to the transaction, returning
// the index of the file contract within the transaction.
AddFileContract(types.FileContract) uint64
// AddFileContractRevision adds a file contract revision to the
// transaction, returning the index of the file contract revision
// within the transaction. When 'Sign' gets called, this revision will
// be left unsigned.
AddFileContractRevision(types.FileContractRevision) uint64
// AddStorageProof adds a storage proof to the transaction, returning
// the index of the storage proof within the transaction.
AddStorageProof(types.StorageProof) uint64
// AddSiafundInput adds a siafund input to the transaction, returning
// the index of the siafund input within the transaction. When 'Sign'
// is called, this input will be left unsigned.
AddSiafundInput(types.SiafundInput) uint64
// AddSiafundOutput adds a siafund output to the transaction, returning
// the index of the siafund output within the transaction.
AddSiafundOutput(types.SiafundOutput) uint64
// AddArbitraryData adds arbitrary data to the transaction, returning
// the index of the data within the transaction.
AddArbitraryData(arb []byte) uint64
// AddTransactionSignature adds a transaction signature to the
// transaction, returning the index of the signature within the
// transaction. The signature should already be valid, and shouldn't
// sign any of the inputs that were added by calling 'FundSiacoins' or
// 'FundSiafunds'.
AddTransactionSignature(types.TransactionSignature) uint64
// Sign will sign any inputs added by 'FundSiacoins' or 'FundSiafunds'
// and return a transaction set that contains all parents prepended to
// the transaction. If more fields need to be added, a new transaction
// builder will need to be created.
//
// If the whole transaction flag is set to true, then the whole
// transaction flag will be set in the covered fields object. If the
// whole transaction flag is set to false, then the covered fields
// object will cover all fields that have already been added to the
// transaction, but will also leave room for more fields to be added.
Sign(wholeTransaction bool) ([]types.Transaction, error)
// View returns the incomplete transaction along with all of its
// parents.
View() (txn types.Transaction, parents []types.Transaction)
// Drop indicates that a transaction is no longer useful, will not be
// broadcast, and that all of the outputs can be reclaimed. 'Drop'
// should only be used before signatures are added.
Drop()
}
// EncryptionManager can encrypt, lock, unlock, and indicate the current
// status of the EncryptionManager.
EncryptionManager interface {
// Encrypt will encrypt the wallet using the input key. Upon
// encryption, a primary seed will be created for the wallet (no seed
// exists prior to this point). If the key is blank, then the hash of
// the seed that is generated will be used as the key.
//
// Encrypt can only be called once throughout the life of the wallet,
// and will return an error on subsequent calls (even after restarting
// the wallet). To reset the wallet, the wallet files must be moved to
// a different directory or deleted.
Encrypt(masterKey crypto.TwofishKey) (Seed, error)
// Encrypted returns whether or not the wallet has been encrypted yet.
// After being encrypted for the first time, the wallet can only be
// unlocked using the encryption password.
Encrypted() bool
// Lock deletes all keys in memory and prevents the wallet from being
// used to spend coins or extract keys until 'Unlock' is called.
Lock() error
// Unlock must be called before the wallet is usable. All wallets and
// wallet seeds are encrypted by default, and the wallet will not know
// which addresses to watch for on the blockchain until unlock has been
// called.
//
// All items in the wallet are encrypted using different keys which are
// derived from the master key.
Unlock(masterKey crypto.TwofishKey) error
// Unlocked returns true if the wallet is currently unlocked, false
// otherwise.
Unlocked() bool
}
// KeyManager manages wallet keys, including the use of seeds, creating and
// loading backups, and providing a layer of compatibility for older wallet
// files.
KeyManager interface {
// AllAddresses returns all addresses that the wallet is able to spend
// from, including unseeded addresses. Addresses are returned sorted in
// byte-order.
AllAddresses() []types.UnlockHash
// AllSeeds returns all of the seeds that are being tracked by the
// wallet, including the primary seed. Only the primary seed is used to
// generate new addresses, but the wallet can spend funds sent to
// public keys generated by any of the seeds returned.
AllSeeds() ([]Seed, error)
// PrimarySeed returns the current primary seed of the wallet,
// unencrypted, with an int indicating how many addresses have been
// consumed.
PrimarySeed() (Seed, uint64, error)
// NextAddress returns a new coin addresses generated from the
// primary seed.
NextAddress() (types.UnlockConditions, error)
// CreateBackup will create a backup of the wallet at the provided
// filepath. The backup will have all seeds and keys.
CreateBackup(string) error
// LoadBackup will load a backup of the wallet from the provided
// address. The backup wallet will be added as an auxiliary seed, not
// as a primary seed.
// LoadBackup(masterKey, backupMasterKey crypto.TwofishKey, string) error
// Load033xWallet will load a version 0.3.3.x wallet from disk and add all of
// the keys in the wallet as unseeded keys.
Load033xWallet(crypto.TwofishKey, string) error
// LoadSeed will recreate a wallet file using the recovery phrase.
// LoadSeed only needs to be called if the original seed file or
// encryption password was lost. The master key is used encrypt the
// recovery seed before saving it to disk.
LoadSeed(crypto.TwofishKey, Seed) error
// LoadSiagKeys will take a set of filepaths that point to a siag key
// and will have the siag keys loaded into the wallet so that they will
// become spendable.
LoadSiagKeys(crypto.TwofishKey, []string) error
}
// Wallet stores and manages siacoins and siafunds. The wallet file is
// encrypted using a user-specified password. Common addresses are all
// dervied from a single address seed.
Wallet interface {
EncryptionManager
KeyManager
// ConfirmedBalance returns the confirmed balance of the wallet, minus
// any outgoing transactions. ConfirmedBalance will include unconfirmed
// refund transacitons.
ConfirmedBalance() (siacoinBalance types.Currency, siafundBalance types.Currency, siacoinClaimBalance types.Currency)
// UnconfirmedBalance returns the unconfirmed balance of the wallet.
// Outgoing funds and incoming funds are reported separately. Refund
// outputs are included, meaning that a sending a single coin to
// someone could result in 'outgoing: 12, incoming: 11'. Siafunds are
// not considered in the unconfirmed balance.
UnconfirmedBalance() (outgoingSiacoins types.Currency, incomingSiacoins types.Currency)
// AddressTransactions returns all of the transactions that are related
// to a given address.
AddressTransactions(types.UnlockHash) []ProcessedTransaction
// AddressUnconfirmedHistory returns all of the unconfirmed
// transactions related to a given address.
AddressUnconfirmedTransactions(types.UnlockHash) []ProcessedTransaction
// Transaction returns the transaction with the given id. The bool
// indicates whether the transaction is in the wallet database. The
// wallet only stores transactions that are related to the wallet.
Transaction(types.TransactionID) (ProcessedTransaction, bool)
// Transactions returns all of the transactions that were confirmed at
// heights [startHeight, endHeight]. Unconfirmed transactions are not
// included.
Transactions(startHeight types.BlockHeight, endHeight types.BlockHeight) ([]ProcessedTransaction, error)
// UnconfirmedTransactions returns all unconfirmed transactions
// relative to the wallet.
UnconfirmedTransactions() []ProcessedTransaction
// RegisterTransaction takes a transaction and its parents and returns
// a TransactionBuilder which can be used to expand the transaction.
// The most typical call is 'RegisterTransaction(types.Transaction{},
// nil)', which registers a new transaction without parents.
RegisterTransaction(t types.Transaction, parents []types.Transaction) TransactionBuilder
// StartTransaction is a convenience method that calls
// RegisterTransaction(types.Transaction{}, nil)
StartTransaction() TransactionBuilder
// SendSiacoins is a tool for sending siacoins from the wallet to an
// address. Sending money usually results in multiple transactions. The
// transactions are automatically given to the transaction pool, and
// are also returned to the caller.
SendSiacoins(amount types.Currency, dest types.UnlockHash) ([]types.Transaction, error)
// SendSiafunds is a tool for sending siafunds from the wallet to an
// address. Sending money usually results in multiple transactions. The
// transactions are automatically given to the transaction pool, and
// are also returned to the caller.
SendSiafunds(amount types.Currency, dest types.UnlockHash) ([]types.Transaction, error)
}
)
// CalculateWalletTransactionID is a helper function for determining the id of
// a wallet transaction.
func CalculateWalletTransactionID(tid types.TransactionID, oid types.OutputID) WalletTransactionID {
return WalletTransactionID(crypto.HashAll(tid, oid))
}
// SeedToString converts a wallet seed to a human friendly string.
func SeedToString(seed Seed, did mnemonics.DictionaryID) (string, error) {
fullChecksum := crypto.HashObject(seed)
checksumSeed := append(seed[:], fullChecksum[:SeedChecksumSize]...)
phrase, err := mnemonics.ToPhrase(checksumSeed, did)
if err != nil {
return "", err
}
return phrase.String(), nil
}
// StringToSeed converts a string to a wallet seed.
func StringToSeed(str string, did mnemonics.DictionaryID) (Seed, error) {
// Decode the string into the checksummed byte slice.
checksumSeedBytes, err := mnemonics.FromString(str, did)
if err != nil {
return Seed{}, err
}
// Copy the seed from the checksummed slice.
var seed Seed
copy(seed[:], checksumSeedBytes)
fullChecksum := crypto.HashObject(seed)
if len(checksumSeedBytes) != crypto.EntropySize+SeedChecksumSize || !bytes.Equal(fullChecksum[:SeedChecksumSize], checksumSeedBytes[crypto.EntropySize:]) {
return Seed{}, errors.New("seed failed checksum verification")
}
return seed, nil
}