/
handler.go
263 lines (228 loc) · 6.47 KB
/
handler.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
package coin
import (
abci "github.com/tendermint/abci/types"
"github.com/tendermint/go-wire/data"
"github.com/tendermint/tmlibs/log"
sdk "github.com/cosmos/cosmos-sdk"
"github.com/cosmos/cosmos-sdk/errors"
"github.com/cosmos/cosmos-sdk/modules/auth"
"github.com/cosmos/cosmos-sdk/modules/ibc"
"github.com/cosmos/cosmos-sdk/stack"
"github.com/cosmos/cosmos-sdk/state"
)
const (
//NameCoin - name space of the coin module
NameCoin = "coin"
// CostSend is GasAllocation per input/output
CostSend = int64(10)
// CostCredit is GasAllocation of a credit allocation
CostCredit = int64(20)
)
// Handler includes an accountant
type Handler struct {
stack.PassInitValidate
}
var _ stack.Dispatchable = Handler{}
// NewHandler - new accountant handler for the coin module
func NewHandler() Handler {
return Handler{}
}
// Name - return name space
func (Handler) Name() string {
return NameCoin
}
// AssertDispatcher - to fulfill Dispatchable interface
func (Handler) AssertDispatcher() {}
// CheckTx checks if there is enough money in the account
func (h Handler) CheckTx(ctx sdk.Context, store state.SimpleDB,
tx sdk.Tx, _ sdk.Checker) (res sdk.CheckResult, err error) {
err = tx.ValidateBasic()
if err != nil {
return res, err
}
switch t := tx.Unwrap().(type) {
case SendTx:
// price based on inputs and outputs
used := int64(len(t.Inputs) + len(t.Outputs))
return sdk.NewCheck(used*CostSend, ""), h.checkSendTx(ctx, store, t)
case CreditTx:
// default price of 20, constant work
return sdk.NewCheck(CostCredit, ""), h.creditTx(ctx, store, t)
}
return res, errors.ErrUnknownTxType(tx.Unwrap())
}
// DeliverTx moves the money
func (h Handler) DeliverTx(ctx sdk.Context, store state.SimpleDB,
tx sdk.Tx, cb sdk.Deliver) (res sdk.DeliverResult, err error) {
err = tx.ValidateBasic()
if err != nil {
return res, err
}
switch t := tx.Unwrap().(type) {
case SendTx:
return h.sendTx(ctx, store, t, cb)
case CreditTx:
return res, h.creditTx(ctx, store, t)
}
return res, errors.ErrUnknownTxType(tx.Unwrap())
}
// InitState - sets the genesis account balance
func (h Handler) InitState(l log.Logger, store state.SimpleDB,
module, key, value string, cb sdk.InitStater) (log string, err error) {
if module != NameCoin {
return "", errors.ErrUnknownModule(module)
}
switch key {
case "account":
return setAccount(store, value)
case "issuer":
return setIssuer(store, value)
}
return "", errors.ErrUnknownKey(key)
}
func (h Handler) sendTx(ctx sdk.Context, store state.SimpleDB,
send SendTx, cb sdk.Deliver) (res sdk.DeliverResult, err error) {
err = checkTx(ctx, send)
if err != nil {
return res, err
}
// deduct from all input accounts
senders := sdk.Actors{}
for _, in := range send.Inputs {
_, err = ChangeCoins(store, in.Address, in.Coins.Negative())
if err != nil {
return res, err
}
senders = append(senders, in.Address)
}
// add to all output accounts
for _, out := range send.Outputs {
// TODO: cleaner way, this makes sure we don't consider
// incoming ibc packets with our chain to be remote packets
if out.Address.ChainID == ctx.ChainID() {
out.Address.ChainID = ""
}
_, err = ChangeCoins(store, out.Address, out.Coins)
if err != nil {
return res, err
}
// now send ibc packet if needed...
if out.Address.ChainID != "" {
// FIXME: if there are many outputs, we need to adjust inputs
// so the amounts in and out match. how?
inputs := make([]TxInput, len(send.Inputs))
for i := range send.Inputs {
inputs[i] = send.Inputs[i]
inputs[i].Address = inputs[i].Address.WithChain(ctx.ChainID())
}
outTx := NewSendTx(inputs, []TxOutput{out})
packet := ibc.CreatePacketTx{
DestChain: out.Address.ChainID,
Permissions: senders,
Tx: outTx,
}
ibcCtx := ctx.WithPermissions(ibc.AllowIBC(NameCoin))
_, err := cb.DeliverTx(ibcCtx, store, packet.Wrap())
if err != nil {
return res, err
}
}
}
// now we build the tags
tags := make([]*abci.KVPair, 0, 1+len(send.Inputs)+len(send.Outputs))
tags = append(tags, abci.KVPairInt("height", int64(ctx.BlockHeight())))
for _, in := range send.Inputs {
addr := in.Address.String()
tags = append(tags, abci.KVPairString("coin.sender", addr))
}
for _, out := range send.Outputs {
addr := out.Address.String()
tags = append(tags, abci.KVPairString("coin.receiver", addr))
}
// a-ok!
return sdk.DeliverResult{Tags: tags}, nil
}
func (h Handler) creditTx(ctx sdk.Context, store state.SimpleDB,
credit CreditTx) error {
// first check permissions!!
info, err := loadHandlerInfo(store)
if err != nil {
return err
}
if info.Issuer.Empty() || !ctx.HasPermission(info.Issuer) {
return errors.ErrUnauthorized()
}
// load up the account
addr := ChainAddr(credit.Debitor)
acct, err := GetAccount(store, addr)
if err != nil {
return err
}
// make and check changes
acct.Coins = acct.Coins.Plus(credit.Credit)
if !acct.Coins.IsNonnegative() {
return ErrInsufficientFunds()
}
acct.Credit = acct.Credit.Plus(credit.Credit)
if !acct.Credit.IsNonnegative() {
return ErrInsufficientCredit()
}
err = storeAccount(store, addr.Bytes(), acct)
return err
}
func checkTx(ctx sdk.Context, send SendTx) error {
// check if all inputs have permission
for _, in := range send.Inputs {
if !ctx.HasPermission(in.Address) {
return errors.ErrUnauthorized()
}
}
return nil
}
func (Handler) checkSendTx(ctx sdk.Context, store state.SimpleDB, send SendTx) error {
err := checkTx(ctx, send)
if err != nil {
return err
}
// now make sure there is money
for _, in := range send.Inputs {
_, err := CheckCoins(store, in.Address, in.Coins.Negative())
if err != nil {
return err
}
}
return nil
}
func setAccount(store state.SimpleDB, value string) (log string, err error) {
var acc GenesisAccount
err = data.FromJSON([]byte(value), &acc)
if err != nil {
return "", err
}
acc.Balance.Sort()
addr, err := acc.GetAddr()
if err != nil {
return "", ErrInvalidAddress()
}
// this sets the permission for a public key signature, use that app
actor := auth.SigPerm(addr)
err = storeAccount(store, actor.Bytes(), acc.ToAccount())
if err != nil {
return "", err
}
return "Success", nil
}
// setIssuer sets a permission for some super-powerful account to
// mint money
func setIssuer(store state.SimpleDB, value string) (log string, err error) {
var issuer sdk.Actor
err = data.FromJSON([]byte(value), &issuer)
if err != nil {
return "", err
}
err = storeIssuer(store, issuer)
if err != nil {
return "", err
}
return "Success", nil
}