OSDN Git Service

add value calculate with lock statement (#2)
[bytom/equity.git] / compiler / compile.go
1 package compiler
2
3 import (
4         "encoding/json"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "strings"
9
10         chainjson "github.com/bytom/encoding/json"
11         "github.com/bytom/errors"
12         "github.com/bytom/protocol/vm"
13         "github.com/bytom/protocol/vm/vmutil"
14 )
15
16 // ValueInfo describes how a blockchain value is used in a contract
17 // clause.
18 type ValueInfo struct {
19         // Name is the clause's name for this value.
20         Name string `json:"name"`
21
22         // Program is the program expression used to the lock the value, if
23         // the value is locked with "lock." If it's unlocked with "unlock"
24         // instead, this is empty.
25         Program string `json:"program,omitempty"`
26
27         // Asset is the expression describing the asset type the value must
28         // have, as it appears in a clause's "requires" section. If this is
29         // the contract value instead, this is empty.
30         Asset string `json:"asset,omitempty"`
31
32         // Amount is the expression describing the amount the value must
33         // have, as it appears in a clause's "requires" section. If this is
34         // the contract value instead, this is empty.
35         Amount string `json:"amount,omitempty"`
36 }
37
38 // ContractArg is an argument with which to instantiate a contract as
39 // a program. Exactly one of B, I, and S should be supplied.
40 type ContractArg struct {
41         B *bool               `json:"boolean,omitempty"`
42         I *int64              `json:"integer,omitempty"`
43         S *chainjson.HexBytes `json:"string,omitempty"`
44 }
45
46 // Compile parses a sequence of Equity contracts from the supplied reader
47 // and produces Contract objects containing the compiled bytecode and
48 // other analysis. If argMap is non-nil, it maps contract names to
49 // lists of arguments with which to instantiate them as programs, with
50 // the results placed in the contract's Program field. A contract
51 // named in argMap but not found in the input is silently ignored.
52 func Compile(r io.Reader) ([]*Contract, error) {
53         inp, err := ioutil.ReadAll(r)
54         if err != nil {
55                 return nil, errors.Wrap(err, "reading input")
56         }
57         contracts, err := parse(inp)
58         if err != nil {
59                 return nil, errors.Wrap(err, "parse error")
60         }
61
62         globalEnv := newEnviron(nil)
63         for _, k := range keywords {
64                 globalEnv.add(k, nilType, roleKeyword)
65         }
66         for _, b := range builtins {
67                 globalEnv.add(b.name, nilType, roleBuiltin)
68         }
69
70         // All contracts must be checked for recursiveness before any are
71         // compiled.
72         for _, contract := range contracts {
73                 contract.Recursive = checkRecursive(contract)
74         }
75
76         for _, contract := range contracts {
77                 err = globalEnv.addContract(contract)
78                 if err != nil {
79                         return nil, err
80                 }
81         }
82
83         for _, contract := range contracts {
84                 err = compileContract(contract, globalEnv)
85                 if err != nil {
86                         return nil, errors.Wrap(err, "compiling contract")
87                 }
88                 for _, clause := range contract.Clauses {
89                         for _, stmt := range clause.statements {
90                                 switch s := stmt.(type) {
91                                 case *lockStatement:
92                                         valueInfo := ValueInfo{
93                                                 Amount:  s.lockedAmount.String(),
94                                                 Asset:   s.lockedAsset.String(),
95                                                 Program: s.program.String(),
96                                         }
97
98                                         clause.Values = append(clause.Values, valueInfo)
99                                 case *unlockStatement:
100                                         valueInfo := ValueInfo{
101                                                 Amount: contract.Value.Amount,
102                                                 Asset:  contract.Value.Asset,
103                                         }
104                                         clause.Values = append(clause.Values, valueInfo)
105                                 }
106                         }
107                 }
108         }
109
110         return contracts, nil
111 }
112
113 func Instantiate(body []byte, params []*Param, recursive bool, args []ContractArg) ([]byte, error) {
114         if len(args) != len(params) {
115                 return nil, fmt.Errorf("got %d argument(s), want %d", len(args), len(params))
116         }
117
118         // typecheck args against param types
119         for i, param := range params {
120                 arg := args[i]
121                 switch param.Type {
122                 case amountType, intType:
123                         if arg.I == nil {
124                                 return nil, fmt.Errorf("type mismatch in arg %d (want integer)", i)
125                         }
126                 case assetType, hashType, progType, pubkeyType, sigType, strType:
127                         if arg.S == nil {
128                                 return nil, fmt.Errorf("type mismatch in arg %d (want string)", i)
129                         }
130                 case boolType:
131                         if arg.B == nil {
132                                 return nil, fmt.Errorf("type mismatch in arg %d (want boolean)", i)
133                         }
134                 }
135         }
136
137         b := vmutil.NewBuilder()
138
139         for i := len(args) - 1; i >= 0; i-- {
140                 a := args[i]
141                 switch {
142                 case a.B != nil:
143                         var n int64
144                         if *a.B {
145                                 n = 1
146                         }
147                         b.AddInt64(n)
148                 case a.I != nil:
149                         b.AddInt64(*a.I)
150                 case a.S != nil:
151                         b.AddData(*a.S)
152                 }
153         }
154
155         if recursive {
156                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
157                 b.AddData(body)
158                 b.AddOp(vm.OP_DEPTH).AddOp(vm.OP_OVER)
159         } else {
160                 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
161                 b.AddOp(vm.OP_DEPTH)
162                 b.AddData(body)
163         }
164         b.AddInt64(0)
165         b.AddOp(vm.OP_CHECKPREDICATE)
166         return b.Build()
167 }
168
169 func compileContract(contract *Contract, globalEnv *environ) error {
170         var err error
171
172         if len(contract.Clauses) == 0 {
173                 return fmt.Errorf("empty contract")
174         }
175         env := newEnviron(globalEnv)
176         for _, p := range contract.Params {
177                 err = env.add(p.Name, p.Type, roleContractParam)
178                 if err != nil {
179                         return err
180                 }
181         }
182
183         // value is spilt with valueAmount and valueAsset
184         if err = env.add(contract.Value.Amount, amountType, roleContractValue); err != nil {
185                 return err
186         }
187         if err = env.add(contract.Value.Asset, assetType, roleContractValue); err != nil {
188                 return err
189         }
190
191         for _, c := range contract.Clauses {
192                 err = env.add(c.Name, nilType, roleClause)
193                 if err != nil {
194                         return err
195                 }
196         }
197
198         err = prohibitSigParams(contract)
199         if err != nil {
200                 return err
201         }
202         err = requireAllParamsUsedInClauses(contract.Params, contract.Clauses)
203         if err != nil {
204                 return err
205         }
206
207         var stk stack
208
209         if len(contract.Clauses) > 1 {
210                 stk = stk.add("<clause selector>")
211         }
212
213         for i := len(contract.Params) - 1; i >= 0; i-- {
214                 p := contract.Params[i]
215                 stk = stk.add(p.Name)
216         }
217
218         if contract.Recursive {
219                 stk = stk.add(contract.Name)
220         }
221
222         b := &builder{}
223
224         if len(contract.Clauses) == 1 {
225                 err = compileClause(b, stk, contract, env, contract.Clauses[0])
226                 if err != nil {
227                         return err
228                 }
229         } else {
230                 if len(contract.Params) > 0 {
231                         // A clause selector is at the bottom of the stack. Roll it to the
232                         // top.
233                         n := len(contract.Params)
234                         if contract.Recursive {
235                                 n++
236                         }
237                         stk = b.addRoll(stk, n) // stack: [<clause params> <contract params> [<maybe contract body>] <clause selector>]
238                 }
239
240                 var stk2 stack
241
242                 // clauses 2..N-1
243                 for i := len(contract.Clauses) - 1; i >= 2; i-- {
244                         stk = b.addDup(stk)                                                   // stack: [... <clause selector> <clause selector>]
245                         stk = b.addInt64(stk, int64(i))                                       // stack: [... <clause selector> <clause selector> <i>]
246                         stk = b.addNumEqual(stk, fmt.Sprintf("(<clause selector> == %d)", i)) // stack: [... <clause selector> <i == clause selector>]
247                         stk = b.addJumpIf(stk, contract.Clauses[i].Name)                      // stack: [... <clause selector>]
248                         stk2 = stk                                                            // stack starts here for clauses 2 through N-1
249                 }
250
251                 // clause 1
252                 stk = b.addJumpIf(stk, contract.Clauses[1].Name) // consumes the clause selector
253
254                 // no jump needed for clause 0
255
256                 for i, clause := range contract.Clauses {
257                         if i > 1 {
258                                 // Clauses 0 and 1 have no clause selector on top of the
259                                 // stack. Clauses 2 and later do.
260                                 stk = stk2
261                         }
262
263                         b.addJumpTarget(stk, clause.Name)
264
265                         if i > 1 {
266                                 stk = b.addDrop(stk)
267                         }
268
269                         err = compileClause(b, stk, contract, env, clause)
270                         if err != nil {
271                                 return errors.Wrapf(err, "compiling clause \"%s\"", clause.Name)
272                         }
273                         b.forgetPendingVerify()
274                         if i < len(contract.Clauses)-1 {
275                                 b.addJump(stk, "_end")
276                         }
277                 }
278                 b.addJumpTarget(stk, "_end")
279         }
280
281         opcodes := optimize(b.opcodes())
282         prog, err := vm.Assemble(opcodes)
283         if err != nil {
284                 return err
285         }
286
287         contract.Body = prog
288         contract.Opcodes = opcodes
289
290         contract.Steps = b.steps()
291
292         return nil
293 }
294
295 func compileClause(b *builder, contractStk stack, contract *Contract, env *environ, clause *Clause) error {
296         var err error
297
298         // copy env to leave outerEnv unchanged
299         env = newEnviron(env)
300         for _, p := range clause.Params {
301                 err = env.add(p.Name, p.Type, roleClauseParam)
302                 if err != nil {
303                         return err
304                 }
305         }
306         assignIndexes(clause)
307
308         var stk stack
309         for _, p := range clause.Params {
310                 // NOTE: the order of clause params is not reversed, unlike
311                 // contract params (and also unlike the arguments to Equity
312                 // function-calls).
313                 stk = stk.add(p.Name)
314         }
315         stk = stk.addFromStack(contractStk)
316
317         // a count of the number of times each variable is referenced
318         counts := make(map[string]int)
319         for _, s := range clause.statements {
320                 s.countVarRefs(counts)
321         }
322
323         for _, s := range clause.statements {
324                 switch stmt := s.(type) {
325                 case *verifyStatement:
326                         stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
327                         if err != nil {
328                                 return errors.Wrapf(err, "in verify statement in clause \"%s\"", clause.Name)
329                         }
330                         stk = b.addVerify(stk)
331
332                         // special-case reporting of certain function calls
333                         if c, ok := stmt.expr.(*callExpr); ok && len(c.args) == 1 {
334                                 if b := referencedBuiltin(c.fn); b != nil {
335                                         switch b.name {
336                                         case "below":
337                                                 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
338                                         case "above":
339                                                 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
340                                         }
341                                 }
342                         }
343
344                 case *lockStatement:
345                         // index
346                         stk = b.addInt64(stk, stmt.index)
347
348                         // TODO: permit more complex expressions for locked,
349                         // like "lock x+y with foo" (?)
350
351                         if stmt.lockedAmount.String() == contract.Value.Amount && stmt.lockedAsset.String() == contract.Value.Asset {
352                                 stk = b.addAmount(stk, contract.Value.Amount)
353                                 stk = b.addAsset(stk, contract.Value.Asset)
354                         } else {
355                                 if strings.Contains(stmt.lockedAmount.String(), contract.Value.Amount) {
356                                         stk = b.addAmount(stk, contract.Value.Amount)
357                                 }
358
359                                 if strings.Contains(stmt.lockedAsset.String(), contract.Value.Asset) {
360                                         stk = b.addAsset(stk, contract.Value.Asset)
361                                 }
362
363                                 // amount
364                                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAmount)
365                                 if err != nil {
366                                         return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
367                                 }
368
369                                 // asset
370                                 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAsset)
371                                 if err != nil {
372                                         return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
373                                 }
374                         }
375
376                         // version
377                         stk = b.addInt64(stk, 1)
378
379                         // prog
380                         stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.program)
381                         if err != nil {
382                                 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
383                         }
384
385                         stk = b.addCheckOutput(stk, fmt.Sprintf("checkOutput(%s, %s, %s)",
386                                 stmt.lockedAmount.String(), stmt.lockedAsset.String(), stmt.program))
387                         stk = b.addVerify(stk)
388
389                 case *unlockStatement:
390                         if len(clause.statements) == 1 {
391                                 // This is the only statement in the clause, make sure TRUE is
392                                 // on the stack.
393                                 stk = b.addBoolean(stk, true)
394                         }
395                 }
396         }
397
398         err = requireAllValuesDisposedOnce(contract, clause)
399         if err != nil {
400                 return err
401         }
402         err = typeCheckClause(contract, clause, env)
403         if err != nil {
404                 return err
405         }
406         err = requireAllParamsUsedInClause(clause.Params, clause)
407         if err != nil {
408                 return err
409         }
410
411         return nil
412 }
413
414 func compileExpr(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, error) {
415         var err error
416
417         switch e := expr.(type) {
418         case *binaryExpr:
419                 // Do typechecking after compiling subexpressions (because other
420                 // compilation errors are more interesting than type mismatch
421                 // errors).
422
423                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.left)
424                 if err != nil {
425                         return stk, errors.Wrapf(err, "in left operand of \"%s\" expression", e.op.op)
426                 }
427                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.right)
428                 if err != nil {
429                         return stk, errors.Wrapf(err, "in right operand of \"%s\" expression", e.op.op)
430                 }
431
432                 lType := e.left.typ(env)
433                 if e.op.left != "" && !(lType == e.op.left || lType == amountType) {
434                         return stk, fmt.Errorf("in \"%s\", left operand has type \"%s\", must be \"%s\"", e, lType, e.op.left)
435                 }
436
437                 rType := e.right.typ(env)
438                 if e.op.right != "" && !(rType == e.op.right || rType == amountType) {
439                         return stk, fmt.Errorf("in \"%s\", right operand has type \"%s\", must be \"%s\"", e, rType, e.op.right)
440                 }
441
442                 switch e.op.op {
443                 case "==", "!=":
444                         if lType != rType {
445                                 // Maybe one is Hash and the other is (more-specific-Hash subtype).
446                                 // TODO(bobg): generalize this mechanism
447                                 if lType == hashType && isHashSubtype(rType) {
448                                         propagateType(contract, clause, env, rType, e.left)
449                                 } else if rType == hashType && isHashSubtype(lType) {
450                                         propagateType(contract, clause, env, lType, e.right)
451                                 } else {
452                                         return stk, fmt.Errorf("type mismatch in \"%s\": left operand has type \"%s\", right operand has type \"%s\"", e, lType, rType)
453                                 }
454                         }
455                         if lType == "Boolean" {
456                                 return stk, fmt.Errorf("in \"%s\": using \"%s\" on Boolean values not allowed", e, e.op.op)
457                         }
458                 }
459
460                 stk = b.addOps(stk.dropN(2), e.op.opcodes, e.String())
461
462         case *unaryExpr:
463                 // Do typechecking after compiling subexpression (because other
464                 // compilation errors are more interesting than type mismatch
465                 // errors).
466
467                 var err error
468                 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.expr)
469                 if err != nil {
470                         return stk, errors.Wrapf(err, "in \"%s\" expression", e.op.op)
471                 }
472
473                 if e.op.operand != "" && e.expr.typ(env) != e.op.operand {
474                         return stk, fmt.Errorf("in \"%s\", operand has type \"%s\", must be \"%s\"", e, e.expr.typ(env), e.op.operand)
475                 }
476                 b.addOps(stk.drop(), e.op.opcodes, e.String())
477
478         case *callExpr:
479                 bi := referencedBuiltin(e.fn)
480                 if bi == nil {
481                         if v, ok := e.fn.(varRef); ok {
482                                 if entry := env.lookup(string(v)); entry != nil && entry.t == contractType {
483                                         clause.Contracts = append(clause.Contracts, entry.c.Name)
484
485                                         partialName := fmt.Sprintf("%s(...)", v)
486                                         stk = b.addData(stk, nil)
487
488                                         if len(e.args) != len(entry.c.Params) {
489                                                 return stk, fmt.Errorf("contract \"%s\" expects %d argument(s), got %d", entry.c.Name, len(entry.c.Params), len(e.args))
490                                         }
491
492                                         for i := len(e.args) - 1; i >= 0; i-- {
493                                                 arg := e.args[i]
494                                                 if entry.c.Params[i].Type != "" && arg.typ(env) != entry.c.Params[i].Type {
495                                                         return stk, fmt.Errorf("argument %d to contract \"%s\" has type \"%s\", must be \"%s\"", i, entry.c.Name, arg.typ(env), entry.c.Params[i].Type)
496                                                 }
497                                                 stk, err = compileExpr(b, stk, contract, clause, env, counts, arg)
498                                                 if err != nil {
499                                                         return stk, err
500                                                 }
501                                                 stk = b.addCatPushdata(stk, partialName)
502                                         }
503
504                                         switch {
505                                         case entry.c == contract:
506                                                 // Recursive call - cannot use entry.c.Body
507                                                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
508                                                 stk, err = compileRef(b, stk, counts, varRef(contract.Name))
509                                                 if err != nil {
510                                                         return stk, errors.Wrap(err, "compiling contract call")
511                                                 }
512                                                 stk = b.addCatPushdata(stk, partialName)
513                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
514                                                 stk = b.addCat(stk, partialName)
515
516                                         case entry.c.Recursive:
517                                                 // Non-recursive call to a (different) recursive contract
518                                                 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
519                                                 if len(entry.c.Body) == 0 {
520                                                         // TODO(bobg): sort input contracts topologically to permit forward calling
521                                                         return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
522                                                 }
523                                                 stk = b.addData(stk, entry.c.Body)
524                                                 stk = b.addCatPushdata(stk, partialName)
525                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
526                                                 stk = b.addCat(stk, partialName)
527
528                                         default:
529                                                 // Non-recursive call to non-recursive contract
530                                                 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
531                                                 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH)})
532                                                 stk = b.addCat(stk, partialName)
533                                                 if len(entry.c.Body) == 0 {
534                                                         // TODO(bobg): sort input contracts topologically to permit forward calling
535                                                         return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
536                                                 }
537                                                 stk = b.addData(stk, entry.c.Body)
538                                                 stk = b.addCatPushdata(stk, partialName)
539                                         }
540                                         stk = b.addData(stk, vm.Int64Bytes(0))
541                                         stk = b.addCatPushdata(stk, partialName)
542                                         stk = b.addData(stk, []byte{byte(vm.OP_CHECKPREDICATE)})
543                                         stk = b.addCat(stk, e.String())
544
545                                         return stk, nil
546                                 }
547                         }
548                         return stk, fmt.Errorf("unknown function \"%s\"", e.fn)
549                 }
550
551                 if len(e.args) != len(bi.args) {
552                         return stk, fmt.Errorf("wrong number of args for \"%s\": have %d, want %d", bi.name, len(e.args), len(bi.args))
553                 }
554
555                 // WARNING WARNING WOOP WOOP
556                 // special-case hack
557                 // WARNING WARNING WOOP WOOP
558                 if bi.name == "checkTxMultiSig" {
559                         if _, ok := e.args[0].(listExpr); !ok {
560                                 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 0", e.args[0])
561                         }
562                         if _, ok := e.args[1].(listExpr); !ok {
563                                 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 1", e.args[1])
564                         }
565
566                         var k1, k2 int
567
568                         stk, k1, err = compileArg(b, stk, contract, clause, env, counts, e.args[1])
569                         if err != nil {
570                                 return stk, err
571                         }
572
573                         // stack: [... sigM ... sig1 M]
574
575                         var altEntry string
576                         stk, altEntry = b.addToAltStack(stk) // stack: [... sigM ... sig1]
577                         stk = b.addTxSigHash(stk)            // stack: [... sigM ... sig1 txsighash]
578
579                         stk, k2, err = compileArg(b, stk, contract, clause, env, counts, e.args[0])
580                         if err != nil {
581                                 return stk, err
582                         }
583
584                         // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N]
585
586                         stk = b.addFromAltStack(stk, altEntry) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N M]
587                         stk = b.addSwap(stk)                   // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 M N]
588                         stk = b.addCheckMultisig(stk, k1+k2, e.String())
589
590                         return stk, nil
591                 }
592
593                 var k int
594
595                 for i := len(e.args) - 1; i >= 0; i-- {
596                         a := e.args[i]
597                         var k2 int
598                         var err error
599                         stk, k2, err = compileArg(b, stk, contract, clause, env, counts, a)
600                         if err != nil {
601                                 return stk, errors.Wrapf(err, "compiling argument %d in call expression", i)
602                         }
603                         k += k2
604                 }
605
606                 // Do typechecking after compiling subexpressions (because other
607                 // compilation errors are more interesting than type mismatch
608                 // errors).
609                 for i, actual := range e.args {
610                         if bi.args[i] != "" && actual.typ(env) != bi.args[i] {
611                                 return stk, fmt.Errorf("argument %d to \"%s\" has type \"%s\", must be \"%s\"", i, bi.name, actual.typ(env), bi.args[i])
612                         }
613                 }
614
615                 stk = b.addOps(stk.dropN(k), bi.opcodes, e.String())
616
617                 // special-case reporting
618                 switch bi.name {
619                 case "sha3", "sha256":
620                         clause.HashCalls = append(clause.HashCalls, HashCall{bi.name, e.args[0].String(), string(e.args[0].typ(env))})
621                 }
622
623         case varRef:
624                 return compileRef(b, stk, counts, e)
625
626         case integerLiteral:
627                 stk = b.addInt64(stk, int64(e))
628
629         case bytesLiteral:
630                 stk = b.addData(stk, []byte(e))
631
632         case booleanLiteral:
633                 stk = b.addBoolean(stk, bool(e))
634
635         case listExpr:
636                 // Lists are excluded here because they disobey the invariant of
637                 // this function: namely, that it increases the stack size by
638                 // exactly one. (A list pushes its items and its length on the
639                 // stack.) But they're OK as function-call arguments because the
640                 // function (presumably) consumes all the stack items added.
641                 return stk, fmt.Errorf("encountered list outside of function-call context")
642         }
643         return stk, nil
644 }
645
646 func compileArg(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, int, error) {
647         var n int
648         if list, ok := expr.(listExpr); ok {
649                 for i := 0; i < len(list); i++ {
650                         elt := list[len(list)-i-1]
651                         var err error
652                         stk, err = compileExpr(b, stk, contract, clause, env, counts, elt)
653                         if err != nil {
654                                 return stk, 0, err
655                         }
656                         n++
657                 }
658                 stk = b.addInt64(stk, int64(len(list)))
659                 n++
660                 return stk, n, nil
661         }
662         var err error
663         stk, err = compileExpr(b, stk, contract, clause, env, counts, expr)
664         return stk, 1, err
665 }
666
667 func compileRef(b *builder, stk stack, counts map[string]int, ref varRef) (stack, error) {
668         depth := stk.find(string(ref))
669         if depth < 0 {
670                 return stk, fmt.Errorf("undefined reference: \"%s\"", ref)
671         }
672
673         var isFinal bool
674         if count, ok := counts[string(ref)]; ok && count > 0 {
675                 count--
676                 counts[string(ref)] = count
677                 isFinal = count == 0
678         }
679
680         switch depth {
681         case 0:
682                 if !isFinal {
683                         stk = b.addDup(stk)
684                 }
685         case 1:
686                 if isFinal {
687                         stk = b.addSwap(stk)
688                 } else {
689                         stk = b.addOver(stk)
690                 }
691         default:
692                 if isFinal {
693                         stk = b.addRoll(stk, depth)
694                 } else {
695                         stk = b.addPick(stk, depth)
696                 }
697         }
698         return stk, nil
699 }
700
701 func (a *ContractArg) UnmarshalJSON(b []byte) error {
702         var m map[string]json.RawMessage
703         err := json.Unmarshal(b, &m)
704         if err != nil {
705                 return err
706         }
707         if r, ok := m["boolean"]; ok {
708                 var bval bool
709                 err = json.Unmarshal(r, &bval)
710                 if err != nil {
711                         return err
712                 }
713                 a.B = &bval
714                 return nil
715         }
716         if r, ok := m["integer"]; ok {
717                 var ival int64
718                 err = json.Unmarshal(r, &ival)
719                 if err != nil {
720                         return err
721                 }
722                 a.I = &ival
723                 return nil
724         }
725         r, ok := m["string"]
726         if !ok {
727                 return fmt.Errorf("contract arg must define one of boolean, integer, string")
728         }
729         var sval chainjson.HexBytes
730         err = json.Unmarshal(r, &sval)
731         if err != nil {
732                 return err
733         }
734         a.S = &sval
735         return nil
736 }