This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 360
/
builder.go
executable file
·259 lines (222 loc) · 7.42 KB
/
builder.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
package account
import (
"context"
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/bytom/blockchain/signers"
"github.com/bytom/blockchain/txbuilder"
"github.com/bytom/common"
"github.com/bytom/consensus"
"github.com/bytom/crypto/ed25519/chainkd"
chainjson "github.com/bytom/encoding/json"
"github.com/bytom/errors"
"github.com/bytom/protocol/bc"
"github.com/bytom/protocol/bc/types"
"github.com/bytom/protocol/vm/vmutil"
)
//DecodeSpendAction unmarshal JSON-encoded data of spend action
func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
a := &spendAction{accounts: m}
err := json.Unmarshal(data, a)
return a, err
}
type spendAction struct {
accounts *Manager
bc.AssetAmount
AccountID string `json:"account_id"`
ClientToken *string `json:"client_token"`
}
func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
var missing []string
if a.AccountID == "" {
missing = append(missing, "account_id")
}
if a.AssetId.IsZero() {
missing = append(missing, "asset_id")
}
if len(missing) > 0 {
return txbuilder.MissingFieldsError(missing...)
}
acct, err := a.accounts.findByID(ctx, a.AccountID)
if err != nil {
return errors.Wrap(err, "get account info")
}
src := source{
AssetID: *a.AssetId,
AccountID: a.AccountID,
}
res, err := a.accounts.utxoDB.Reserve(src, a.Amount, a.ClientToken, b.MaxTime())
if err != nil {
return errors.Wrap(err, "reserving utxos")
}
// Cancel the reservation if the build gets rolled back.
b.OnRollback(canceler(ctx, a.accounts, res.ID))
for _, r := range res.UTXOs {
txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
if err != nil {
return errors.Wrap(err, "creating inputs")
}
err = b.AddInput(txInput, sigInst)
if err != nil {
return errors.Wrap(err, "adding inputs")
}
}
if res.Change > 0 {
acp, err := a.accounts.CreateAddress(ctx, a.AccountID, true)
if err != nil {
return errors.Wrap(err, "creating control program")
}
// Don't insert the control program until callbacks are executed.
a.accounts.insertControlProgramDelayed(ctx, b, acp)
err = b.AddOutput(types.NewTxOutput(*a.AssetId, res.Change, acp.ControlProgram))
if err != nil {
return errors.Wrap(err, "adding change output")
}
}
return nil
}
//DecodeSpendUTXOAction unmarshal JSON-encoded data of spend utxo action
func (m *Manager) DecodeSpendUTXOAction(data []byte) (txbuilder.Action, error) {
a := &spendUTXOAction{accounts: m}
err := json.Unmarshal(data, a)
return a, err
}
type spendUTXOAction struct {
accounts *Manager
OutputID *bc.Hash `json:"output_id"`
ClientToken *string `json:"client_token"`
}
func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
if a.OutputID == nil {
return txbuilder.MissingFieldsError("output_id")
}
res, err := a.accounts.utxoDB.ReserveUTXO(ctx, *a.OutputID, a.ClientToken, b.MaxTime())
if err != nil {
return err
}
b.OnRollback(canceler(ctx, a.accounts, res.ID))
var accountSigner *signers.Signer
if len(res.Source.AccountID) != 0 {
account, err := a.accounts.findByID(ctx, res.Source.AccountID)
if err != nil {
return err
}
accountSigner = account.Signer
}
txInput, sigInst, err := UtxoToInputs(accountSigner, res.UTXOs[0])
if err != nil {
return err
}
return b.AddInput(txInput, sigInst)
}
// Best-effort cancellation attempt to put in txbuilder.BuildResult.Rollback.
func canceler(ctx context.Context, m *Manager, rid uint64) func() {
return func() {
if err := m.utxoDB.Cancel(ctx, rid); err != nil {
log.WithField("error", err).Error("Best-effort cancellation attempt to put in txbuilder.BuildResult.Rollback")
}
}
}
// UtxoToInputs convert an utxo to the txinput
func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
sigInst := &txbuilder.SigningInstruction{}
if signer == nil {
return txInput, sigInst, nil
}
path := signers.Path(signer, signers.AccountKeySpace, u.ControlProgramIndex)
if u.Address == "" {
sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
return txInput, sigInst, nil
}
address, err := common.DecodeAddress(u.Address, &consensus.MainNetParams)
if err != nil {
return nil, nil, err
}
switch address.(type) {
case *common.AddressWitnessPubKeyHash:
sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
derivedPK := derivedXPubs[0].PublicKey()
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
case *common.AddressWitnessScriptHash:
sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
path := signers.Path(signer, signers.AccountKeySpace, u.ControlProgramIndex)
derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
derivedPKs := chainkd.XPubKeys(derivedXPubs)
script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
if err != nil {
return nil, nil, err
}
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
default:
return nil, nil, errors.New("unsupport address type")
}
return txInput, sigInst, nil
}
//NewControlAction create new control action
func (m *Manager) NewControlAction(amt bc.AssetAmount, accountID string, refData chainjson.Map) txbuilder.Action {
return &controlAction{
accounts: m,
AssetAmount: amt,
AccountID: accountID,
ReferenceData: refData,
}
}
//DecodeControlAction unmarshal JSON-encoded data of control action
func (m *Manager) DecodeControlAction(data []byte) (txbuilder.Action, error) {
a := &controlAction{accounts: m}
err := json.Unmarshal(data, a)
return a, err
}
type controlAction struct {
accounts *Manager
bc.AssetAmount
AccountID string `json:"account_id"`
ReferenceData chainjson.Map `json:"reference_data"`
}
func (a *controlAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
var missing []string
if a.AccountID == "" {
missing = append(missing, "account_id")
}
if a.AssetId.IsZero() {
missing = append(missing, "asset_id")
}
if len(missing) > 0 {
return txbuilder.MissingFieldsError(missing...)
}
// Produce a control program, but don't insert it into the database yet.
acp, err := a.accounts.CreateAddress(ctx, a.AccountID, false)
if err != nil {
return err
}
a.accounts.insertControlProgramDelayed(ctx, b, acp)
return b.AddOutput(types.NewTxOutput(*a.AssetId, a.Amount, acp.ControlProgram))
}
// insertControlProgramDelayed takes a template builder and an account
// control program that hasn't been inserted to the database yet. It
// registers callbacks on the TemplateBuilder so that all of the template's
// account control programs are batch inserted if building the rest of
// the template is successful.
func (m *Manager) insertControlProgramDelayed(ctx context.Context, b *txbuilder.TemplateBuilder, acp *CtrlProgram) {
m.delayedACPsMu.Lock()
m.delayedACPs[b] = append(m.delayedACPs[b], acp)
m.delayedACPsMu.Unlock()
b.OnRollback(func() {
m.delayedACPsMu.Lock()
delete(m.delayedACPs, b)
m.delayedACPsMu.Unlock()
})
b.OnBuild(func() error {
m.delayedACPsMu.Lock()
acps := m.delayedACPs[b]
delete(m.delayedACPs, b)
m.delayedACPsMu.Unlock()
// Insert all of the account control programs at once.
if len(acps) == 0 {
return nil
}
return m.insertAccountControlProgram(ctx, acps...)
})
}