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)
224 if len(contract.Clauses) == 1 {
225 err = compileClause(b, stk, contract, env, contract.Clauses[0])
230 if len(contract.Params) > 0 {
231 // A clause selector is at the bottom of the stack. Roll it to the
233 n := len(contract.Params)
234 if contract.Recursive {
237 stk = b.addRoll(stk, n) // stack: [<clause params> <contract params> [<maybe contract body>] <clause selector>]
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
252 stk = b.addJumpIf(stk, contract.Clauses[1].Name) // consumes the clause selector
254 // no jump needed for clause 0
256 for i, clause := range contract.Clauses {
258 // Clauses 0 and 1 have no clause selector on top of the
259 // stack. Clauses 2 and later do.
263 b.addJumpTarget(stk, clause.Name)
269 err = compileClause(b, stk, contract, env, clause)
271 return errors.Wrapf(err, "compiling clause \"%s\"", clause.Name)
273 b.forgetPendingVerify()
274 if i < len(contract.Clauses)-1 {
275 b.addJump(stk, "_end")
278 b.addJumpTarget(stk, "_end")
281 opcodes := optimize(b.opcodes())
282 prog, err := vm.Assemble(opcodes)
288 contract.Opcodes = opcodes
290 contract.Steps = b.steps()
295 func compileClause(b *builder, contractStk stack, contract *Contract, env *environ, clause *Clause) error {
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)
306 assignIndexes(clause)
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
313 stk = stk.add(p.Name)
315 stk = stk.addFromStack(contractStk)
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)
323 for _, s := range clause.statements {
324 switch stmt := s.(type) {
325 case *defineStatement:
327 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
329 return errors.Wrapf(err, "in define statement in clause \"%s\"", clause.Name)
332 // check variable type
333 if stmt.expr.typ(env) != stmt.varName.Type {
334 return fmt.Errorf("expression in define statement in clause \"%s\" has type \"%s\", must be \"%s\"",
335 clause.Name, stmt.expr.typ(env), stmt.varName.Type)
339 stk.str = stmt.varName.Name
341 // add environ for define variable
342 if err = env.add(stmt.varName.Name, stmt.varName.Type, roleClauseVariable); err != nil {
346 case *verifyStatement:
347 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
349 return errors.Wrapf(err, "in verify statement in clause \"%s\"", clause.Name)
351 stk = b.addVerify(stk)
353 // special-case reporting of certain function calls
354 if c, ok := stmt.expr.(*callExpr); ok && len(c.args) == 1 {
355 if b := referencedBuiltin(c.fn); b != nil {
358 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
360 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
367 stk = b.addInt64(stk, stmt.index)
369 // TODO: permit more complex expressions for locked,
370 // like "lock x+y with foo" (?)
372 if stmt.lockedAmount.String() == contract.Value.Amount && stmt.lockedAsset.String() == contract.Value.Asset {
373 stk = b.addAmount(stk, contract.Value.Amount)
374 stk = b.addAsset(stk, contract.Value.Asset)
376 if strings.Contains(stmt.lockedAmount.String(), contract.Value.Amount) {
377 stk = b.addAmount(stk, contract.Value.Amount)
380 if strings.Contains(stmt.lockedAsset.String(), contract.Value.Asset) {
381 stk = b.addAsset(stk, contract.Value.Asset)
385 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAmount)
387 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
391 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAsset)
393 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
398 stk = b.addInt64(stk, 1)
401 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.program)
403 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
406 stk = b.addCheckOutput(stk, fmt.Sprintf("checkOutput(%s, %s, %s)",
407 stmt.lockedAmount.String(), stmt.lockedAsset.String(), stmt.program))
408 stk = b.addVerify(stk)
410 case *unlockStatement:
411 if len(clause.statements) == 1 {
412 // This is the only statement in the clause, make sure TRUE is
414 stk = b.addBoolean(stk, true)
419 err = requireAllValuesDisposedOnce(contract, clause)
423 err = typeCheckClause(contract, clause, env)
427 err = requireAllParamsUsedInClause(clause.Params, clause)
435 func compileExpr(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, error) {
438 switch e := expr.(type) {
440 // Do typechecking after compiling subexpressions (because other
441 // compilation errors are more interesting than type mismatch
444 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.left)
446 return stk, errors.Wrapf(err, "in left operand of \"%s\" expression", e.op.op)
448 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.right)
450 return stk, errors.Wrapf(err, "in right operand of \"%s\" expression", e.op.op)
453 lType := e.left.typ(env)
454 if e.op.left != "" && !(lType == e.op.left || lType == amountType) {
455 return stk, fmt.Errorf("in \"%s\", left operand has type \"%s\", must be \"%s\"", e, lType, e.op.left)
458 rType := e.right.typ(env)
459 if e.op.right != "" && !(rType == e.op.right || rType == amountType) {
460 return stk, fmt.Errorf("in \"%s\", right operand has type \"%s\", must be \"%s\"", e, rType, e.op.right)
466 // Maybe one is Hash and the other is (more-specific-Hash subtype).
467 // TODO(bobg): generalize this mechanism
468 if lType == hashType && isHashSubtype(rType) {
469 propagateType(contract, clause, env, rType, e.left)
470 } else if rType == hashType && isHashSubtype(lType) {
471 propagateType(contract, clause, env, lType, e.right)
473 return stk, fmt.Errorf("type mismatch in \"%s\": left operand has type \"%s\", right operand has type \"%s\"", e, lType, rType)
476 if lType == "Boolean" {
477 return stk, fmt.Errorf("in \"%s\": using \"%s\" on Boolean values not allowed", e, e.op.op)
481 stk = b.addOps(stk.dropN(2), e.op.opcodes, e.String())
484 // Do typechecking after compiling subexpression (because other
485 // compilation errors are more interesting than type mismatch
489 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.expr)
491 return stk, errors.Wrapf(err, "in \"%s\" expression", e.op.op)
494 if e.op.operand != "" && e.expr.typ(env) != e.op.operand {
495 return stk, fmt.Errorf("in \"%s\", operand has type \"%s\", must be \"%s\"", e, e.expr.typ(env), e.op.operand)
497 b.addOps(stk.drop(), e.op.opcodes, e.String())
500 bi := referencedBuiltin(e.fn)
502 if v, ok := e.fn.(varRef); ok {
503 if entry := env.lookup(string(v)); entry != nil && entry.t == contractType {
504 clause.Contracts = append(clause.Contracts, entry.c.Name)
506 partialName := fmt.Sprintf("%s(...)", v)
507 stk = b.addData(stk, nil)
509 if len(e.args) != len(entry.c.Params) {
510 return stk, fmt.Errorf("contract \"%s\" expects %d argument(s), got %d", entry.c.Name, len(entry.c.Params), len(e.args))
513 for i := len(e.args) - 1; i >= 0; i-- {
515 if entry.c.Params[i].Type != "" && arg.typ(env) != entry.c.Params[i].Type {
516 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)
518 stk, err = compileExpr(b, stk, contract, clause, env, counts, arg)
522 stk = b.addCatPushdata(stk, partialName)
526 case entry.c == contract:
527 // Recursive call - cannot use entry.c.Body
528 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
529 stk, err = compileRef(b, stk, counts, varRef(contract.Name))
531 return stk, errors.Wrap(err, "compiling contract call")
533 stk = b.addCatPushdata(stk, partialName)
534 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
535 stk = b.addCat(stk, partialName)
537 case entry.c.Recursive:
538 // Non-recursive call to a (different) recursive contract
539 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
540 if len(entry.c.Body) == 0 {
541 // TODO(bobg): sort input contracts topologically to permit forward calling
542 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
544 stk = b.addData(stk, entry.c.Body)
545 stk = b.addCatPushdata(stk, partialName)
546 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
547 stk = b.addCat(stk, partialName)
550 // Non-recursive call to non-recursive contract
551 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
552 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH)})
553 stk = b.addCat(stk, partialName)
554 if len(entry.c.Body) == 0 {
555 // TODO(bobg): sort input contracts topologically to permit forward calling
556 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
558 stk = b.addData(stk, entry.c.Body)
559 stk = b.addCatPushdata(stk, partialName)
561 stk = b.addData(stk, vm.Int64Bytes(0))
562 stk = b.addCatPushdata(stk, partialName)
563 stk = b.addData(stk, []byte{byte(vm.OP_CHECKPREDICATE)})
564 stk = b.addCat(stk, e.String())
569 return stk, fmt.Errorf("unknown function \"%s\"", e.fn)
572 if len(e.args) != len(bi.args) {
573 return stk, fmt.Errorf("wrong number of args for \"%s\": have %d, want %d", bi.name, len(e.args), len(bi.args))
576 // WARNING WARNING WOOP WOOP
578 // WARNING WARNING WOOP WOOP
579 if bi.name == "checkTxMultiSig" {
580 if _, ok := e.args[0].(listExpr); !ok {
581 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 0", e.args[0])
583 if _, ok := e.args[1].(listExpr); !ok {
584 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 1", e.args[1])
589 stk, k1, err = compileArg(b, stk, contract, clause, env, counts, e.args[1])
594 // stack: [... sigM ... sig1 M]
597 stk, altEntry = b.addToAltStack(stk) // stack: [... sigM ... sig1]
598 stk = b.addTxSigHash(stk) // stack: [... sigM ... sig1 txsighash]
600 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, e.args[0])
605 // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N]
607 stk = b.addFromAltStack(stk, altEntry) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N M]
608 stk = b.addSwap(stk) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 M N]
609 stk = b.addCheckMultisig(stk, k1+k2, e.String())
616 for i := len(e.args) - 1; i >= 0; i-- {
620 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, a)
622 return stk, errors.Wrapf(err, "compiling argument %d in call expression", i)
627 // Do typechecking after compiling subexpressions (because other
628 // compilation errors are more interesting than type mismatch
630 for i, actual := range e.args {
631 if bi.args[i] != "" && actual.typ(env) != bi.args[i] {
632 return stk, fmt.Errorf("argument %d to \"%s\" has type \"%s\", must be \"%s\"", i, bi.name, actual.typ(env), bi.args[i])
636 stk = b.addOps(stk.dropN(k), bi.opcodes, e.String())
638 // special-case reporting
640 case "sha3", "sha256":
641 clause.HashCalls = append(clause.HashCalls, HashCall{bi.name, e.args[0].String(), string(e.args[0].typ(env))})
645 return compileRef(b, stk, counts, e)
648 stk = b.addInt64(stk, int64(e))
651 stk = b.addData(stk, []byte(e))
654 stk = b.addBoolean(stk, bool(e))
657 // Lists are excluded here because they disobey the invariant of
658 // this function: namely, that it increases the stack size by
659 // exactly one. (A list pushes its items and its length on the
660 // stack.) But they're OK as function-call arguments because the
661 // function (presumably) consumes all the stack items added.
662 return stk, fmt.Errorf("encountered list outside of function-call context")
667 func compileArg(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, int, error) {
669 if list, ok := expr.(listExpr); ok {
670 for i := 0; i < len(list); i++ {
671 elt := list[len(list)-i-1]
673 stk, err = compileExpr(b, stk, contract, clause, env, counts, elt)
679 stk = b.addInt64(stk, int64(len(list)))
684 stk, err = compileExpr(b, stk, contract, clause, env, counts, expr)
688 func compileRef(b *builder, stk stack, counts map[string]int, ref varRef) (stack, error) {
689 depth := stk.find(string(ref))
691 return stk, fmt.Errorf("undefined reference: \"%s\"", ref)
695 if count, ok := counts[string(ref)]; ok && count > 0 {
697 counts[string(ref)] = count
714 stk = b.addRoll(stk, depth)
716 stk = b.addPick(stk, depth)
722 func (a *ContractArg) UnmarshalJSON(b []byte) error {
723 var m map[string]json.RawMessage
724 err := json.Unmarshal(b, &m)
728 if r, ok := m["boolean"]; ok {
730 err = json.Unmarshal(r, &bval)
737 if r, ok := m["integer"]; ok {
739 err = json.Unmarshal(r, &ival)
748 return fmt.Errorf("contract arg must define one of boolean, integer, string")
750 var sval chainjson.HexBytes
751 err = json.Unmarshal(r, &sval)