-
Notifications
You must be signed in to change notification settings - Fork 4
/
builder.go
308 lines (259 loc) · 7.67 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
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
package builder
import (
"context"
"errors"
"strings"
"sync"
"github.com/cosmos/cosmos-sdk/client"
sdkclient "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdktypes "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/histolabs/metro/app/encoding"
"github.com/histolabs/metro/pkg/consts"
"google.golang.org/grpc"
)
// KeyringSigner uses a keyring to sign and build celestia-app transactions
type KeyringSigner struct {
keyring.Keyring
keyringAccName string
chainID string
secondaryChainID string
encCfg encoding.Config
sync.RWMutex
acc authtypes.AccountI
}
// NewKeyringSigner returns a new KeyringSigner using the provided keyring
func NewKeyringSigner(encCfg encoding.Config, ring keyring.Keyring, name string, chainID string) *KeyringSigner {
ids := strings.SplitN(chainID, consts.ChainIDSeparator, 2)
secondaryChainID := ""
if len(ids) > 1 {
secondaryChainID = ids[1]
}
return &KeyringSigner{
Keyring: ring,
keyringAccName: name,
chainID: chainID,
secondaryChainID: secondaryChainID,
encCfg: encCfg,
}
}
// Update queries the application to find the latest account number and
// sequence, updating the respective internal fields. The internal account
// number must be set by this method or by manually calling k.SetAccountNumber
// in order for any built transactions to be valid
func (k *KeyringSigner) UpdateAccount(ctx context.Context, conn *grpc.ClientConn) error {
info, err := k.Key(k.keyringAccName)
if err != nil {
return err
}
addr, err := info.GetAddress()
if err != nil {
return err
}
acc, err := QueryAccount(ctx, conn, k.encCfg, addr.String())
if err != nil {
return err
}
k.Lock()
defer k.Unlock()
k.acc = acc
return nil
}
func (k *KeyringSigner) UpdateAccountFromClient(clientCtx client.Context) error {
rec := k.GetSignerInfo()
addr, err := rec.GetAddress()
if err != nil {
return err
}
accNum, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr)
if err != nil {
return err
}
k.SetAccountNumber(accNum)
k.SetSequence(seq)
return nil
}
// NewTxBuilder returns the default sdk Tx builder using the celestia-app encoding config
func (k *KeyringSigner) NewTxBuilder(opts ...TxBuilderOption) sdkclient.TxBuilder {
builder := k.encCfg.TxConfig.NewTxBuilder()
for _, opt := range opts {
builder = opt(builder)
}
return builder
}
// BuildSignedTx creates and signs a sdk.Tx that contains the provided message. The interal
// account number must be set by calling k.QueryAccountNumber or by manually setting it via
// k.SetAccountNumber for the built transactions to be valid.
func (k *KeyringSigner) BuildSignedTx(builder sdkclient.TxBuilder, isSecondary bool, msg ...sdktypes.Msg) (authsigning.Tx, error) {
k.RLock()
sequence := k.acc.GetSequence()
if isSecondary {
sequence = k.acc.GetSecondarySequence(k.secondaryChainID)
builder.SetSecondaryChainID(k.secondaryChainID)
}
k.RUnlock()
// set the msg
err := builder.SetMsgs(msg...)
if err != nil {
return nil, err
}
// lookup account info
keyInfo, err := k.Key(k.keyringAccName)
if err != nil {
return nil, err
}
pub, err := keyInfo.GetPubKey()
if err != nil {
return nil, err
}
// we must first set an empty signature in order generate
// the correct sign bytes
sigV2 := signing.SignatureV2{
PubKey: pub,
Data: &signing.SingleSignatureData{
SignMode: signing.SignMode_SIGN_MODE_DIRECT,
Signature: nil,
},
Sequence: sequence,
}
// set the empty signature
err = builder.SetSignatures(sigV2)
if err != nil {
return nil, err
}
signerData, err := k.GetSignerData(isSecondary)
if err != nil {
return nil, err
}
// Generate the bytes to be signed.
bytesToSign, err := k.encCfg.TxConfig.SignModeHandler().GetSignBytes(
signing.SignMode_SIGN_MODE_DIRECT,
signerData,
builder.GetTx(),
)
if err != nil {
return nil, err
}
addr, err := keyInfo.GetAddress()
if err != nil {
return nil, err
}
// Sign those bytes using the keyring. we are ignoring the returned public key
sigBytes, _, err := k.SignByAddress(addr, bytesToSign)
if err != nil {
return nil, err
}
// Construct the SignatureV2 struct, this time including a real signature
sigV2 = signing.SignatureV2{
PubKey: pub,
Data: &signing.SingleSignatureData{
SignMode: signing.SignMode_SIGN_MODE_DIRECT,
Signature: sigBytes,
},
Sequence: sequence,
}
// set the final signature
err = builder.SetSignatures(sigV2)
if err != nil {
return nil, err
}
// return the signed transaction
return builder.GetTx(), nil
}
// SetAccountNumber manually sets the underlying account number
func (k *KeyringSigner) SetAccountNumber(n uint64) error {
k.Lock()
defer k.Unlock()
return k.acc.SetAccountNumber(n)
}
// SetSequence manually sets the underlying sequence number
func (k *KeyringSigner) SetSequence(n uint64) error {
k.Lock()
defer k.Unlock()
return k.acc.SetSequence(n)
}
// SetSecondarySequence manually sets the underlying secondary sequence number
func (k *KeyringSigner) SetSecondarySequence(id string, n uint64) error {
k.Lock()
defer k.Unlock()
return k.acc.SetSecondarySequence(id, n)
}
// SetKeyringAccName manually sets the underlying keyring account name
func (k *KeyringSigner) SetKeyringAccName(name string) {
k.keyringAccName = name
}
// GetSignerInfo returns the signer info for the KeyringSigner's account. panics
// if the account in KeyringSigner does not exist.
func (k *KeyringSigner) GetSignerInfo() *keyring.Record {
info, err := k.Key(k.keyringAccName)
if err != nil {
panic(err)
}
return info
}
func (k *KeyringSigner) GetSignerData(isSecondary bool) (authsigning.SignerData, error) {
k.RLock()
accountNumber := k.acc.GetAccountNumber()
sequence := k.acc.GetSequence()
if isSecondary {
if k.secondaryChainID == "" {
k.RUnlock()
return authsigning.SignerData{}, errors.New("no secondary chain-id set for secondary tx")
}
accountNumber = 0
sequence = k.acc.GetSecondarySequence(k.secondaryChainID)
}
k.RUnlock()
record, err := k.Key(k.keyringAccName)
if err != nil {
return authsigning.SignerData{}, err
}
pubKey, err := record.GetPubKey()
if err != nil {
return authsigning.SignerData{}, err
}
address := pubKey.Address()
return authsigning.SignerData{
Address: address.String(),
ChainID: k.chainID,
AccountNumber: accountNumber,
Sequence: sequence,
PubKey: pubKey,
}, nil
}
// EncodeTx uses the keyring signer's encoding config to encode the provided sdk transaction
func (k *KeyringSigner) EncodeTx(tx sdktypes.Tx) ([]byte, error) {
return k.encCfg.TxConfig.TxEncoder()(tx)
}
// BroadcastTx uses the provided grpc connection to broadcast a signed and encoded transaction
func BroadcastTx(ctx context.Context, conn *grpc.ClientConn, mode tx.BroadcastMode, txBytes []byte) (*tx.BroadcastTxResponse, error) {
txClient := tx.NewServiceClient(conn)
return txClient.BroadcastTx(
ctx,
&tx.BroadcastTxRequest{
Mode: mode,
TxBytes: txBytes,
},
)
}
// QueryAccount fetches the account number and sequence number from the celestia-app node.
func QueryAccount(ctx context.Context, conn *grpc.ClientConn, encCfg encoding.Config, address string) (authtypes.AccountI, error) {
qclient := authtypes.NewQueryClient(conn)
resp, err := qclient.Account(
ctx,
&authtypes.QueryAccountRequest{Address: address},
)
if err != nil {
return nil, err
}
var acc authtypes.AccountI
err = encCfg.InterfaceRegistry.UnpackAny(resp.Account, &acc)
if err != nil {
return nil, err
}
return acc, nil
}