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"
16 // ValueInfo describes how a blockchain value is used in a contract
18 type ValueInfo struct {
19 // Name is the clause's name for this value.
20 Name string `json:"name"`
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"`
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"`
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"`
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"`
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)
55 return nil, errors.Wrap(err, "reading input")
57 contracts, err := parse(inp)
59 return nil, errors.Wrap(err, "parse error")
62 globalEnv := newEnviron(nil)
63 for _, k := range keywords {
64 globalEnv.add(k, nilType, roleKeyword)
66 for _, b := range builtins {
67 globalEnv.add(b.name, nilType, roleBuiltin)
70 // All contracts must be checked for recursiveness before any are
72 for _, contract := range contracts {
73 contract.Recursive = checkRecursive(contract)
76 for _, contract := range contracts {
77 err = globalEnv.addContract(contract)
83 for _, contract := range contracts {
84 err = compileContract(contract, globalEnv)
86 return nil, errors.Wrap(err, "compiling contract")
88 for _, clause := range contract.Clauses {
89 for _, stmt := range clause.statements {
90 switch s := stmt.(type) {
92 valueInfo := ValueInfo{
93 Amount: s.lockedAmount.String(),
94 Asset: s.lockedAsset.String(),
95 Program: s.program.String(),
98 clause.Values = append(clause.Values, valueInfo)
99 case *unlockStatement:
100 valueInfo := ValueInfo{
101 Amount: contract.Value.Amount,
102 Asset: contract.Value.Asset,
104 clause.Values = append(clause.Values, valueInfo)
110 return contracts, nil
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))
118 // typecheck args against param types
119 for i, param := range params {
122 case amountType, intType:
124 return nil, fmt.Errorf("type mismatch in arg %d (want integer)", i)
126 case assetType, hashType, progType, pubkeyType, sigType, strType:
128 return nil, fmt.Errorf("type mismatch in arg %d (want string)", i)
132 return nil, fmt.Errorf("type mismatch in arg %d (want boolean)", i)
137 b := vmutil.NewBuilder()
139 for i := len(args) - 1; i >= 0; i-- {
156 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
158 b.AddOp(vm.OP_DEPTH).AddOp(vm.OP_OVER)
160 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
165 b.AddOp(vm.OP_CHECKPREDICATE)
169 func compileContract(contract *Contract, globalEnv *environ) error {
172 if len(contract.Clauses) == 0 {
173 return fmt.Errorf("empty contract")
175 env := newEnviron(globalEnv)
176 for _, p := range contract.Params {
177 err = env.add(p.Name, p.Type, roleContractParam)
183 // value is spilt with valueAmount and valueAsset
184 if err = env.add(contract.Value.Amount, amountType, roleContractValue); err != nil {
187 if err = env.add(contract.Value.Asset, assetType, roleContractValue); err != nil {
191 for _, c := range contract.Clauses {
192 err = env.add(c.Name, nilType, roleClause)
198 err = prohibitSigParams(contract)
202 err = requireAllParamsUsedInClauses(contract.Params, contract.Clauses)
209 if len(contract.Clauses) > 1 {
210 stk = stk.add("<clause selector>")
213 for i := len(contract.Params) - 1; i >= 0; i-- {
214 p := contract.Params[i]
215 stk = stk.add(p.Name)
218 if contract.Recursive {
219 stk = stk.add(contract.Name)
223 sequence := 0 // sequence is used to count the number of ifStatements
225 if len(contract.Clauses) == 1 {
226 err = compileClause(b, stk, contract, env, contract.Clauses[0], &sequence)
231 if len(contract.Params) > 0 {
232 // A clause selector is at the bottom of the stack. Roll it to the
234 n := len(contract.Params)
235 if contract.Recursive {
238 stk = b.addRoll(stk, n) // stack: [<clause params> <contract params> [<maybe contract body>] <clause selector>]
244 for i := len(contract.Clauses) - 1; i >= 2; i-- {
245 stk = b.addDup(stk) // stack: [... <clause selector> <clause selector>]
246 stk = b.addInt64(stk, int64(i)) // stack: [... <clause selector> <clause selector> <i>]
247 stk = b.addNumEqual(stk, fmt.Sprintf("(<clause selector> == %d)", i)) // stack: [... <clause selector> <i == clause selector>]
248 stk = b.addJumpIf(stk, contract.Clauses[i].Name) // stack: [... <clause selector>]
249 stk2 = stk // stack starts here for clauses 2 through N-1
253 stk = b.addJumpIf(stk, contract.Clauses[1].Name) // consumes the clause selector
255 // no jump needed for clause 0
257 for i, clause := range contract.Clauses {
259 // Clauses 0 and 1 have no clause selector on top of the
260 // stack. Clauses 2 and later do.
264 b.addJumpTarget(stk, clause.Name)
270 err = compileClause(b, stk, contract, env, clause, &sequence)
272 return errors.Wrapf(err, "compiling clause \"%s\"", clause.Name)
274 b.forgetPendingVerify()
275 if i < len(contract.Clauses)-1 {
276 b.addJump(stk, "_end")
279 b.addJumpTarget(stk, "_end")
282 opcodes := optimize(b.opcodes())
283 prog, err := vm.Assemble(opcodes)
289 contract.Opcodes = opcodes
291 contract.Steps = b.steps()
296 func compileClause(b *builder, contractStk stack, contract *Contract, env *environ, clause *Clause, sequence *int) error {
299 // copy env to leave outerEnv unchanged
300 env = newEnviron(env)
301 for _, p := range clause.Params {
302 err = env.add(p.Name, p.Type, roleClauseParam)
307 assignIndexes(clause)
310 for _, p := range clause.Params {
311 // NOTE: the order of clause params is not reversed, unlike
312 // contract params (and also unlike the arguments to Equity
314 stk = stk.add(p.Name)
316 stk = stk.addFromStack(contractStk)
318 // a count of the number of times each variable is referenced
319 counts := make(map[string]int)
320 for _, s := range clause.statements {
321 s.countVarRefs(counts)
322 if stmt, ok := s.(*ifStatement); ok {
323 for _, trueStmt := range stmt.body.trueBody {
324 trueStmt.countVarRefs(counts)
327 for _, falseStmt := range stmt.body.falseBody {
328 falseStmt.countVarRefs(counts)
333 for _, stat := range clause.statements {
334 if stk, err = compileStatement(b, stk, contract, env, clause, counts, stat, sequence); err != nil {
339 err = requireAllValuesDisposedOnce(contract, clause)
343 err = typeCheckClause(contract, clause, env)
347 err = requireAllParamsUsedInClause(clause.Params, clause)
355 func compileStatement(b *builder, stk stack, contract *Contract, env *environ, clause *Clause, counts map[string]int, stat statement, sequence *int) (stack, error) {
357 switch stmt := stat.(type) {
359 // sequence add 1 when the statement is ifStatement
361 strSequence := fmt.Sprintf("%d", *sequence)
363 // compile condition expression
364 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.condition)
366 return stk, errors.Wrapf(err, "in check condition of ifStatement in clause \"%s\"", clause.Name)
369 // jump to falseBody when condition is false, while the JUMPIF instruction will be run success when
370 // the value of dataStack is true, therefore add this check
371 conditionExpr := stk.str
372 stk = b.addBoolean(stk, false)
373 stk = b.addEqual(stk, fmt.Sprintf("(%s == false)", conditionExpr)) // stack: [... <condition_result == false>]
377 if len(stmt.body.falseBody) != 0 {
378 label = "else_" + strSequence
380 label = "endif_" + strSequence
382 stk = b.addJumpIf(stk, label)
383 b.addJumpTarget(stk, "if_"+strSequence)
385 // temporary store stack and counts for falseBody
387 elseCounts := make(map[string]int)
388 for k, v := range counts {
392 // compile trueBody statements
393 if len(stmt.body.trueBody) != 0 {
394 for _, st := range stmt.body.trueBody {
395 st.countVarRefs(counts)
398 for _, st := range stmt.body.trueBody {
399 if stk, err = compileStatement(b, stk, contract, env, clause, counts, st, sequence); err != nil {
405 // compile falseBody statements
406 if len(stmt.body.falseBody) != 0 {
407 counts := make(map[string]int)
408 for k, v := range elseCounts {
412 for _, st := range stmt.body.falseBody {
413 st.countVarRefs(counts)
417 b.addJump(stk, "endif_"+strSequence)
418 b.addJumpTarget(stk, "else_"+strSequence)
420 for _, st := range stmt.body.falseBody {
421 if stk, err = compileStatement(b, stk, contract, env, clause, counts, st, sequence); err != nil {
426 b.addJumpTarget(stk, "endif_"+strSequence)
428 case *defineStatement:
430 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
432 return stk, errors.Wrapf(err, "in define statement in clause \"%s\"", clause.Name)
435 // check variable type
436 if stmt.expr.typ(env) != stmt.varName.Type {
437 return stk, fmt.Errorf("expression in define statement in clause \"%s\" has type \"%s\", must be \"%s\"",
438 clause.Name, stmt.expr.typ(env), stmt.varName.Type)
442 stk.str = stmt.varName.Name
444 // add environ for define variable
445 if err = env.add(stmt.varName.Name, stmt.varName.Type, roleClauseVariable); err != nil {
449 case *verifyStatement:
450 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
452 return stk, errors.Wrapf(err, "in verify statement in clause \"%s\"", clause.Name)
454 stk = b.addVerify(stk)
456 // special-case reporting of certain function calls
457 if c, ok := stmt.expr.(*callExpr); ok && len(c.args) == 1 {
458 if b := referencedBuiltin(c.fn); b != nil {
461 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
463 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
470 stk = b.addInt64(stk, stmt.index)
472 // TODO: permit more complex expressions for locked,
473 // like "lock x+y with foo" (?)
475 if stmt.lockedAmount.String() == contract.Value.Amount && stmt.lockedAsset.String() == contract.Value.Asset {
476 stk = b.addAmount(stk, contract.Value.Amount)
477 stk = b.addAsset(stk, contract.Value.Asset)
479 if strings.Contains(stmt.lockedAmount.String(), contract.Value.Amount) {
480 stk = b.addAmount(stk, contract.Value.Amount)
483 if strings.Contains(stmt.lockedAsset.String(), contract.Value.Asset) {
484 stk = b.addAsset(stk, contract.Value.Asset)
488 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAmount)
490 return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
494 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAsset)
496 return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
501 stk = b.addInt64(stk, 1)
504 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.program)
506 return stk, errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
509 stk = b.addCheckOutput(stk, fmt.Sprintf("checkOutput(%s, %s, %s)",
510 stmt.lockedAmount.String(), stmt.lockedAsset.String(), stmt.program))
511 stk = b.addVerify(stk)
513 case *unlockStatement:
514 if len(clause.statements) == 1 {
515 // This is the only statement in the clause, make sure TRUE is
517 stk = b.addBoolean(stk, true)
524 func compileExpr(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, error) {
527 switch e := expr.(type) {
529 // Do typechecking after compiling subexpressions (because other
530 // compilation errors are more interesting than type mismatch
533 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.left)
535 return stk, errors.Wrapf(err, "in left operand of \"%s\" expression", e.op.op)
537 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.right)
539 return stk, errors.Wrapf(err, "in right operand of \"%s\" expression", e.op.op)
542 lType := e.left.typ(env)
543 if e.op.left != "" && !(lType == e.op.left || lType == amountType) {
544 return stk, fmt.Errorf("in \"%s\", left operand has type \"%s\", must be \"%s\"", e, lType, e.op.left)
547 rType := e.right.typ(env)
548 if e.op.right != "" && !(rType == e.op.right || rType == amountType) {
549 return stk, fmt.Errorf("in \"%s\", right operand has type \"%s\", must be \"%s\"", e, rType, e.op.right)
555 // Maybe one is Hash and the other is (more-specific-Hash subtype).
556 // TODO(bobg): generalize this mechanism
557 if lType == hashType && isHashSubtype(rType) {
558 propagateType(contract, clause, env, rType, e.left)
559 } else if rType == hashType && isHashSubtype(lType) {
560 propagateType(contract, clause, env, lType, e.right)
562 return stk, fmt.Errorf("type mismatch in \"%s\": left operand has type \"%s\", right operand has type \"%s\"", e, lType, rType)
565 if lType == "Boolean" {
566 return stk, fmt.Errorf("in \"%s\": using \"%s\" on Boolean values not allowed", e, e.op.op)
570 stk = b.addOps(stk.dropN(2), e.op.opcodes, e.String())
573 // Do typechecking after compiling subexpression (because other
574 // compilation errors are more interesting than type mismatch
578 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.expr)
580 return stk, errors.Wrapf(err, "in \"%s\" expression", e.op.op)
583 if e.op.operand != "" && e.expr.typ(env) != e.op.operand {
584 return stk, fmt.Errorf("in \"%s\", operand has type \"%s\", must be \"%s\"", e, e.expr.typ(env), e.op.operand)
586 b.addOps(stk.drop(), e.op.opcodes, e.String())
589 bi := referencedBuiltin(e.fn)
591 if v, ok := e.fn.(varRef); ok {
592 if entry := env.lookup(string(v)); entry != nil && entry.t == contractType {
593 clause.Contracts = append(clause.Contracts, entry.c.Name)
595 partialName := fmt.Sprintf("%s(...)", v)
596 stk = b.addData(stk, nil)
598 if len(e.args) != len(entry.c.Params) {
599 return stk, fmt.Errorf("contract \"%s\" expects %d argument(s), got %d", entry.c.Name, len(entry.c.Params), len(e.args))
602 for i := len(e.args) - 1; i >= 0; i-- {
604 if entry.c.Params[i].Type != "" && arg.typ(env) != entry.c.Params[i].Type {
605 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)
607 stk, err = compileExpr(b, stk, contract, clause, env, counts, arg)
611 stk = b.addCatPushdata(stk, partialName)
615 case entry.c == contract:
616 // Recursive call - cannot use entry.c.Body
617 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
618 stk, err = compileRef(b, stk, counts, varRef(contract.Name))
620 return stk, errors.Wrap(err, "compiling contract call")
622 stk = b.addCatPushdata(stk, partialName)
623 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
624 stk = b.addCat(stk, partialName)
626 case entry.c.Recursive:
627 // Non-recursive call to a (different) recursive contract
628 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
629 if len(entry.c.Body) == 0 {
630 // TODO(bobg): sort input contracts topologically to permit forward calling
631 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
633 stk = b.addData(stk, entry.c.Body)
634 stk = b.addCatPushdata(stk, partialName)
635 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
636 stk = b.addCat(stk, partialName)
639 // Non-recursive call to non-recursive contract
640 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
641 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH)})
642 stk = b.addCat(stk, partialName)
643 if len(entry.c.Body) == 0 {
644 // TODO(bobg): sort input contracts topologically to permit forward calling
645 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
647 stk = b.addData(stk, entry.c.Body)
648 stk = b.addCatPushdata(stk, partialName)
650 stk = b.addData(stk, vm.Int64Bytes(0))
651 stk = b.addCatPushdata(stk, partialName)
652 stk = b.addData(stk, []byte{byte(vm.OP_CHECKPREDICATE)})
653 stk = b.addCat(stk, e.String())
658 return stk, fmt.Errorf("unknown function \"%s\"", e.fn)
661 if len(e.args) != len(bi.args) {
662 return stk, fmt.Errorf("wrong number of args for \"%s\": have %d, want %d", bi.name, len(e.args), len(bi.args))
665 // WARNING WARNING WOOP WOOP
667 // WARNING WARNING WOOP WOOP
668 if bi.name == "checkTxMultiSig" {
669 if _, ok := e.args[0].(listExpr); !ok {
670 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 0", e.args[0])
672 if _, ok := e.args[1].(listExpr); !ok {
673 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 1", e.args[1])
678 stk, k1, err = compileArg(b, stk, contract, clause, env, counts, e.args[1])
683 // stack: [... sigM ... sig1 M]
686 stk, altEntry = b.addToAltStack(stk) // stack: [... sigM ... sig1]
687 stk = b.addTxSigHash(stk) // stack: [... sigM ... sig1 txsighash]
689 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, e.args[0])
694 // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N]
696 stk = b.addFromAltStack(stk, altEntry) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N M]
697 stk = b.addSwap(stk) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 M N]
698 stk = b.addCheckMultisig(stk, k1+k2, e.String())
705 for i := len(e.args) - 1; i >= 0; i-- {
709 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, a)
711 return stk, errors.Wrapf(err, "compiling argument %d in call expression", i)
716 // Do typechecking after compiling subexpressions (because other
717 // compilation errors are more interesting than type mismatch
719 for i, actual := range e.args {
720 if bi.args[i] != "" && actual.typ(env) != bi.args[i] {
721 return stk, fmt.Errorf("argument %d to \"%s\" has type \"%s\", must be \"%s\"", i, bi.name, actual.typ(env), bi.args[i])
725 stk = b.addOps(stk.dropN(k), bi.opcodes, e.String())
727 // special-case reporting
729 case "sha3", "sha256":
730 clause.HashCalls = append(clause.HashCalls, HashCall{bi.name, e.args[0].String(), string(e.args[0].typ(env))})
734 return compileRef(b, stk, counts, e)
737 stk = b.addInt64(stk, int64(e))
740 stk = b.addData(stk, []byte(e))
743 stk = b.addBoolean(stk, bool(e))
746 // Lists are excluded here because they disobey the invariant of
747 // this function: namely, that it increases the stack size by
748 // exactly one. (A list pushes its items and its length on the
749 // stack.) But they're OK as function-call arguments because the
750 // function (presumably) consumes all the stack items added.
751 return stk, fmt.Errorf("encountered list outside of function-call context")
756 func compileArg(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, int, error) {
758 if list, ok := expr.(listExpr); ok {
759 for i := 0; i < len(list); i++ {
760 elt := list[len(list)-i-1]
762 stk, err = compileExpr(b, stk, contract, clause, env, counts, elt)
768 stk = b.addInt64(stk, int64(len(list)))
773 stk, err = compileExpr(b, stk, contract, clause, env, counts, expr)
777 func compileRef(b *builder, stk stack, counts map[string]int, ref varRef) (stack, error) {
778 depth := stk.find(string(ref))
780 return stk, fmt.Errorf("undefined reference: \"%s\"", ref)
784 if count, ok := counts[string(ref)]; ok && count > 0 {
786 counts[string(ref)] = count
803 stk = b.addRoll(stk, depth)
805 stk = b.addPick(stk, depth)
811 func (a *ContractArg) UnmarshalJSON(b []byte) error {
812 var m map[string]json.RawMessage
813 err := json.Unmarshal(b, &m)
817 if r, ok := m["boolean"]; ok {
819 err = json.Unmarshal(r, &bval)
826 if r, ok := m["integer"]; ok {
828 err = json.Unmarshal(r, &ival)
837 return fmt.Errorf("contract arg must define one of boolean, integer, string")
839 var sval chainjson.HexBytes
840 err = json.Unmarshal(r, &sval)