/
push_key.go
293 lines (252 loc) · 9.01 KB
/
push_key.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
package modules
import (
"fmt"
"github.com/make-os/kit/config"
"github.com/make-os/kit/crypto/ed25519"
modulestypes "github.com/make-os/kit/modules/types"
"github.com/make-os/kit/node/services"
types2 "github.com/make-os/kit/rpc/types"
"github.com/make-os/kit/types"
"github.com/make-os/kit/types/api"
"github.com/make-os/kit/types/constants"
"github.com/make-os/kit/types/core"
"github.com/make-os/kit/types/txns"
"github.com/make-os/kit/util"
"github.com/make-os/kit/util/errors"
"github.com/make-os/kit/util/identifier"
"github.com/spf13/cast"
"github.com/c-bata/go-prompt"
"github.com/robertkrimen/otto"
)
// PushKeyModule manages and provides access to push keys.
type PushKeyModule struct {
modulestypes.ModuleCommon
cfg *config.AppConfig
service services.Service
logic core.Logic
}
// NewAttachablePushKeyModule creates an instance of PushKeyModule suitable in attach mode
func NewAttachablePushKeyModule(cfg *config.AppConfig, client types2.Client) *PushKeyModule {
return &PushKeyModule{ModuleCommon: modulestypes.ModuleCommon{Client: client}, cfg: cfg}
}
// NewPushKeyModule creates an instance of PushKeyModule
func NewPushKeyModule(cfg *config.AppConfig, service services.Service, logic core.Logic) *PushKeyModule {
return &PushKeyModule{cfg: cfg, service: service, logic: logic}
}
// methods are functions exposed in the special namespace of this module.
func (m *PushKeyModule) methods() []*modulestypes.VMMember {
return []*modulestypes.VMMember{{Name: "register", Value: m.Register, Description: "Register a push key"},
{Name: "unregister", Value: m.Unregister, Description: "Remove a push key from the network"},
{Name: "update", Value: m.Update, Description: "Update a previously registered push key"},
{Name: "find", Value: m.Find, Description: "Find a push key"},
{Name: "getByAddress", Value: m.GetByAddress, Description: "Get push keys belonging to a user address"},
{Name: "getOwner", Value: m.GetAccountOfOwner, Description: "Get the account of a push key owner"},
}
}
// globals are functions exposed in the VM's global namespace
func (m *PushKeyModule) globals() []*modulestypes.VMMember {
return []*modulestypes.VMMember{}
}
// ConfigureVM configures the JS context and return
// any number of console prompt suggestions
func (m *PushKeyModule) ConfigureVM(vm *otto.Otto) prompt.Completer {
// Set the namespace object
nsMap := map[string]interface{}{}
util.VMSet(vm, constants.NamespacePushKey, nsMap)
// add methods functions
for _, f := range m.methods() {
nsMap[f.Name] = f.Value
funcFullName := fmt.Sprintf("%s.%s", constants.NamespacePushKey, f.Name)
m.Suggestions = append(m.Suggestions, prompt.Suggest{Text: funcFullName, Description: f.Description})
}
// Register global functions
for _, f := range m.globals() {
_ = vm.Set(f.Name, f.Value)
m.Suggestions = append(m.Suggestions, prompt.Suggest{Text: f.Name, Description: f.Description})
}
return m.Completer
}
// Register registers a push key with the network.
//
// ARGS:
// params <map>
// - params.nonce <number|string>: he senders next account nonce
// - params.fee <number|string>: The transaction fee to pay
// - params.timestamp <number>: The unix timestamp
// - params.pubKey <string>:The public key
// - params.scopes <string|[]string>: A list of repo or namespace where the key can be used.
// - params.feeCap <number|string>: The max. amount of fee the key can spend
//
// options <[]interface{}>
// - options[0] key <string>: The signer's private key
// - options[1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURNS object <map>:
// - hash <string>: The transaction hash
// - address <string>: The push key address
func (m *PushKeyModule) Register(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareTxRegisterPushKey()
if err = tx.FromMap(params); err != nil {
panic(errors.ReqErr(400, StatusCodeInvalidParam, "params", err.Error()))
}
printPayload, signingKey := finalizeTx(tx, m.logic, m.Client, options...)
if printPayload {
return tx.ToMap()
}
if m.IsAttached() {
resp, err := m.Client.PushKey().Register(&api.BodyRegisterPushKey{
PublicKey: tx.PublicKey,
Scopes: tx.Scopes,
FeeCap: cast.ToFloat64(tx.FeeCap.String()),
Nonce: tx.Nonce,
Fee: cast.ToFloat64(tx.Fee.String()),
SigningKey: ed25519.NewKeyFromPrivKey(signingKey),
})
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(errors.ReqErr(400, StatusCodeMempoolAddFail, "", err.Error()))
}
pk := ed25519.MustPubKeyFromBytes(tx.PublicKey.Bytes())
return map[string]interface{}{
"hash": hash,
"address": pk.PushAddr().String(),
}
}
// Update updates a push key
//
// ARGS:
// params <map>
// - params.nonce <number|string>: The senders next account nonce
// - params.fee <number|string>: The transaction fee to pay
// - params.timestamp <number>: The unix timestamp
// - params.id <string>: The target push key ID
// - params.addScopes <string|[]string>: Provide repo names or namespaces where the key can be used.
// - params.removeScopes <int|[]int>: Select indices of existing scopes to be deleted.
// - params.feeCap <number|string>: The max. amount of fee the key can spend
//
// options <[]interface{}>
// - options[0] key <string>: The signer's private key
// - options[1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURNS object <map>:
// - hash <string>: The transaction hash
func (m *PushKeyModule) Update(params map[string]interface{}, options ...interface{}) util.Map {
var err error
// Decode parameters into a transaction object
var tx = txns.NewBareTxUpDelPushKey()
if err = tx.FromMap(params); err != nil {
panic(errors.ReqErr(400, StatusCodeInvalidParam, "params", err.Error()))
}
tx.Delete = false
if printPayload, _ := finalizeTx(tx, m.logic, nil, options...); printPayload {
return tx.ToMap()
}
// Process the transaction
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(errors.ReqErr(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// Unregister removes a push key from the network
//
// ARGS:
// - params <map>
// - params.nonce <number|string>: The senders next account nonce
// - params.fee <number|string>: The transaction fee to pay
// - params.timestamp <number>: The unix timestamp
// - params.id <string>: The target push key ID
//
// options <[]interface{}>
// - options[0] key <string>: The signer's private key
// - options[1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURNS object <map>:
// - hash <string>: The transaction hash
func (m *PushKeyModule) Unregister(params map[string]interface{}, options ...interface{}) util.Map {
var err error
// Decode parameters into a transaction object
var tx = txns.NewBareTxUpDelPushKey()
if err = tx.FromMap(params); err != nil {
panic(errors.ReqErr(400, StatusCodeInvalidParam, "params", err.Error()))
}
tx.Delete = true
tx.FeeCap = ""
tx.AddScopes = nil
tx.RemoveScopes = nil
if printPayload, _ := finalizeTx(tx, m.logic, nil, options...); printPayload {
return tx.ToMap()
}
// Process the transaction
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(errors.ReqErr(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// Find finds and returns a push key
//
// ARGS:
// address: The push key address
// [height]: The target block height to query (default: latest)
//
// RETURNS state.PushKey
func (m *PushKeyModule) Find(address string, height ...uint64) util.Map {
if address == "" {
panic(errors.ReqErr(400, StatusCodeInvalidParam, "id", "push key id is required"))
}
h := uint64(0)
if len(height) > 0 {
h = height[0]
}
o := m.logic.PushKeyKeeper().Get(address, h)
if o.IsNil() {
panic(errors.ReqErr(404, StatusCodePushKeyNotFound, "", types.ErrPushKeyUnknown.Error()))
}
return util.ToMap(o)
}
// GetByAddress returns a list of push key addresses owned by the given user address
//
// ARGS:
// address: An address of an account
//
// RETURNS: List of push key ids
func (m *PushKeyModule) GetByAddress(address string) []string {
return m.logic.PushKeyKeeper().GetByAddress(address)
}
// GetAccountOfOwner returns the account of the key owner
//
// ARGS:
// address: The push key address
// [height]: The target block height to query (default: latest)
//
// RETURNS state.Account
func (m *PushKeyModule) GetAccountOfOwner(address string, height ...uint64) util.Map {
h := uint64(0)
if len(height) > 0 {
h = height[0]
}
if m.IsAttached() {
resp, err := m.Client.PushKey().GetOwner(address, h)
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
pushKey := m.Find(address, height...)
acct := m.logic.AccountKeeper().Get(pushKey["address"].(identifier.Address), h)
if acct.IsNil() {
panic(errors.ReqErr(404, StatusCodeAccountNotFound, "address", types.ErrAccountUnknown.Error()))
}
return util.ToMap(acct)
}