【比特币】脚本

来源:互联网 发布:淘宝详情模板 编辑:程序博客网 时间:2024/04/30 11:47


Script

Bitcoin uses a scripting system for transactions. Forth-like, Script is simple, stack-based, and processed from left to right. It is purposefully not Turing-complete, with no loops.

A script is essentially a list of instructions recorded with each transaction that describe how the next person wanting to spend the Bitcoins being transferred can gain access to them. The script for a typical Bitcoin transfer to destination Bitcoin address D simply encumbers future spending of the bitcoins with two things: the spender must provide

  1. a public key that, when hashed, yields destination address D embedded in the script, and
  2. a signature to show evidence of the private key corresponding to the public key just provided.

Scripting provides the flexibility to change the parameters of what's needed to spend transferred Bitcoins. For example, the scripting system could be used to require two private keys, or a combination of several, or even no keys at all.

A transaction is valid if nothing in the combined script triggers failure and the top stack item is true (non-zero). The party who originally sent the Bitcoins now being spent, dictates the script operations that will occur last in order to release them for use in another transaction. The party wanting to spend them must provide the input(s) to the previously recorded script that results in those operations occurring last leaving behind true (non-zero).

The stacks hold byte vectors. When used as numbers, byte vectors are interpreted as little-endian variable-length integers with the most significant bit determining the sign of the integer. Thus 0x81 represents -1. 0x80 is another representation of zero (so called negative 0). Positive 0 is represented by a null-length vector. Byte vectors are interpreted as Booleans where False is represented by any representation of zero, and True is represented by any representation of non-zero.

Contents

  • 1 Words
    • 1.1 Constants
    • 1.2 Flow control
    • 1.3 Stack
    • 1.4 Splice
    • 1.5 Bitwise logic
    • 1.6 Arithmetic
    • 1.7 Crypto
    • 1.8 Pseudo-words
    • 1.9 Reserved words
  • 2 Scripts
    • 2.1 Standard Transaction to Bitcoin address (pay-to-pubkey-hash)
    • 2.2 Standard Generation Transaction (pay-to-pubkey)
    • 2.3 Provably Unspendable/Prunable Outputs
    • 2.4 Anyone-Can-Spend Outputs
    • 2.5 Transaction puzzle
  • 3 See Also

Words

This is a list of all Script words (commands/functions). Some of the more complicated opcodes are disabled out of concern that the client might have a bug in their implementation; if a transaction using such an opcode were to be included in the chain any fix would risk forking the chain.

True=1 and False=0.

Constants

When talking about scripts, these value-pushing words are usually omitted.

WordOpcodeHexInputOutputDescriptionOP_0, OP_FALSE00x00Nothing.(empty value)An empty array of bytes is pushed onto the stack. (This is not a no-op: an item is added to the stack.)N/A1-750x01-0x4b(special)dataThe next opcode bytes is data to be pushed onto the stackOP_PUSHDATA1760x4c(special)dataThe next byte contains the number of bytes to be pushed onto the stack.OP_PUSHDATA2770x4d(special)dataThe next two bytes contain the number of bytes to be pushed onto the stack.OP_PUSHDATA4780x4e(special)dataThe next four bytes contain the number of bytes to be pushed onto the stack.OP_1NEGATE790x4fNothing.-1The number -1 is pushed onto the stack.OP_1, OP_TRUE810x51Nothing.1The number 1 is pushed onto the stack.OP_2-OP_1682-960x52-0x60Nothing.2-16The number in the word name (2-16) is pushed onto the stack.

Flow control

WordOpcodeHexInputOutputDescriptionOP_NOP970x61NothingNothingDoes nothing.OP_IF990x63<expression> if [statements] [else [statements]]* endifIf the top stack value is not 0, the statements are executed. The top stack value is removed.OP_NOTIF1000x64<expression> if [statements] [else [statements]]* endifIf the top stack value is 0, the statements are executed. The top stack value is removed.OP_ELSE1030x67<expression> if [statements] [else [statements]]* endifIf the preceding OP_IF or OP_NOTIF or OP_ELSE was not executed then these statements are and if the preceding OP_IF or OP_NOTIF or OP_ELSE was executed then these statements are not.OP_ENDIF1040x68<expression> if [statements] [else [statements]]* endifEnds an if/else block. All blocks must end, or the transaction is invalid. An OP_ENDIF without OP_IF earlier is also invalid.OP_VERIFY1050x69True / falseNothing / FalseMarks transaction as invalid if top stack value is not true.OP_RETURN1060x6aNothingNothingMarks transaction as invalid.

Stack

WordOpcodeHexInputOutputDescriptionOP_TOALTSTACK1070x6bx1(alt)x1Puts the input onto the top of the alt stack. Removes it from the main stack.OP_FROMALTSTACK1080x6c(alt)x1x1Puts the input onto the top of the main stack. Removes it from the alt stack.OP_IFDUP1150x73xx / x xIf the top stack value is not 0, duplicate it.OP_DEPTH1160x74Nothing<Stack size>Puts the number of stack items onto the stack.OP_DROP1170x75xNothingRemoves the top stack item.OP_DUP1180x76xx xDuplicates the top stack item.OP_NIP1190x77x1 x2x2Removes the second-to-top stack item.OP_OVER1200x78x1 x2x1 x2 x1Copies the second-to-top stack item to the top.OP_PICK1210x79xn ... x2 x1 x0 <n>xn ... x2 x1 x0 xnThe item n back in the stack is copied to the top.OP_ROLL1220x7axn ... x2 x1 x0 <n>... x2 x1 x0 xnThe item n back in the stack is moved to the top.OP_ROT1230x7bx1 x2 x3x2 x3 x1The top three items on the stack are rotated to the left.OP_SWAP1240x7cx1 x2x2 x1The top two items on the stack are swapped.OP_TUCK1250x7dx1 x2x2 x1 x2The item at the top of the stack is copied and inserted before the second-to-top item.OP_2DROP1090x6dx1 x2NothingRemoves the top two stack items.OP_2DUP1100x6ex1 x2x1 x2 x1 x2Duplicates the top two stack items.OP_3DUP1110x6fx1 x2 x3x1 x2 x3 x1 x2 x3Duplicates the top three stack items.OP_2OVER1120x70x1 x2 x3 x4x1 x2 x3 x4 x1 x2Copies the pair of items two spaces back in the stack to the front.OP_2ROT1130x71x1 x2 x3 x4 x5 x6x3 x4 x5 x6 x1 x2The fifth and sixth items back are moved to the top of the stack.OP_2SWAP1140x72x1 x2 x3 x4x3 x4 x1 x2Swaps the top two pairs of items.

Splice

If any opcode marked as disabled is present in a script, it must abort and fail.

WordOpcodeHexInputOutputDescriptionOP_CAT1260x7ex1 x2outConcatenates two strings. disabled.OP_SUBSTR1270x7fin begin sizeoutReturns a section of a string. disabled.OP_LEFT1280x80in sizeoutKeeps only characters left of the specified point in a string. disabled.OP_RIGHT1290x81in sizeoutKeeps only characters right of the specified point in a string. disabled.OP_SIZE1300x82inin sizePushes the string length of the top element of the stack (without popping it).

Bitwise logic

If any opcode marked as disabled is present in a script, it must abort and fail.

WordOpcodeHexInputOutputDescriptionOP_INVERT1310x83inoutFlips all of the bits in the input. disabled.OP_AND1320x84x1 x2outBoolean and between each bit in the inputs. disabled.OP_OR1330x85x1 x2outBoolean or between each bit in the inputs. disabled.OP_XOR1340x86x1 x2outBoolean exclusive or between each bit in the inputs. disabled.OP_EQUAL1350x87x1 x2True / falseReturns 1 if the inputs are exactly equal, 0 otherwise.OP_EQUALVERIFY1360x88x1 x2True / falseSame as OP_EQUAL, but runs OP_VERIFY afterward.

Arithmetic

Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output.

If any input value for any of these commands is longer than 4 bytes, the script must abort and fail. If any opcode marked as disabled is present in a script - it must also abort and fail.

WordOpcodeHexInputOutputDescriptionOP_1ADD1390x8binout1 is added to the input.OP_1SUB1400x8cinout1 is subtracted from the input.OP_2MUL1410x8dinoutThe input is multiplied by 2. disabled.OP_2DIV1420x8einoutThe input is divided by 2. disabled.OP_NEGATE1430x8finoutThe sign of the input is flipped.OP_ABS1440x90inoutThe input is made positive.OP_NOT1450x91inoutIf the input is 0 or 1, it is flipped. Otherwise the output will be 0.OP_0NOTEQUAL1460x92inoutReturns 0 if the input is 0. 1 otherwise.OP_ADD1470x93a bouta is added to b.OP_SUB1480x94a boutb is subtracted from a.OP_MUL1490x95a bouta is multiplied by b. disabled.OP_DIV1500x96a bouta is divided by b. disabled.OP_MOD1510x97a boutReturns the remainder after dividing a by b. disabled.OP_LSHIFT1520x98a boutShifts a left b bits, preserving sign. disabled.OP_RSHIFT1530x99a boutShifts a right b bits, preserving sign. disabled.OP_BOOLAND1540x9aa boutIf both a and b are not 0, the output is 1. Otherwise 0.OP_BOOLOR1550x9ba boutIf a or b is not 0, the output is 1. Otherwise 0.OP_NUMEQUAL1560x9ca boutReturns 1 if the numbers are equal, 0 otherwise.OP_NUMEQUALVERIFY1570x9da boutSame as OP_NUMEQUAL, but runs OP_VERIFY afterward.OP_NUMNOTEQUAL1580x9ea boutReturns 1 if the numbers are not equal, 0 otherwise.OP_LESSTHAN1590x9fa boutReturns 1 if a is less than b, 0 otherwise.OP_GREATERTHAN1600xa0a boutReturns 1 if a is greater than b, 0 otherwise.OP_LESSTHANOREQUAL1610xa1a boutReturns 1 if a is less than or equal to b, 0 otherwise.OP_GREATERTHANOREQUAL1620xa2a boutReturns 1 if a is greater than or equal to b, 0 otherwise.OP_MIN1630xa3a boutReturns the smaller of a and b.OP_MAX1640xa4a boutReturns the larger of a and b.OP_WITHIN1650xa5x min maxoutReturns 1 if x is within the specified range (left-inclusive), 0 otherwise.

Crypto

WordOpcodeHexInputOutputDescriptionOP_RIPEMD1601660xa6inhashThe input is hashed using RIPEMD-160.OP_SHA11670xa7inhashThe input is hashed using SHA-1.OP_SHA2561680xa8inhashThe input is hashed using SHA-256.OP_HASH1601690xa9inhashThe input is hashed twice: first with SHA-256 and then with RIPEMD-160.OP_HASH2561700xaainhashThe input is hashed two times with SHA-256.OP_CODESEPARATOR1710xabNothingNothingAll of the signature checking words will only match signatures to the data after the most recently-executed OP_CODESEPARATOR.OP_CHECKSIG1720xacsig pubkeyTrue / falseThe entire transaction's outputs, inputs, and script (from the most recently-executed OP_CODESEPARATOR to the end) are hashed. The signature used by OP_CHECKSIG must be a valid signature for this hash and public key. If it is, 1 is returned, 0 otherwise.OP_CHECKSIGVERIFY1730xadsig pubkeyTrue / falseSame as OP_CHECKSIG, but OP_VERIFY is executed afterward.OP_CHECKMULTISIG1740xaex sig1 sig2 ... <number of signatures> pub1 pub2 <number of public keys>True / FalseFor each signature and public key pair, OP_CHECKSIG is executed. If more public keys than signatures are listed, some key/sig pairs can fail. All signatures need to match a public key. If all signatures are valid, 1 is returned, 0 otherwise. Due to a bug, one extra unused value is removed from the stack.OP_CHECKMULTISIGVERIFY1750xafx sig1 sig2 ... <number of signatures> pub1 pub2 ... <number of public keys>True / FalseSame as OP_CHECKMULTISIG, but OP_VERIFY is executed afterward.

Pseudo-words

These words are used internally for assisting with transaction matching. They are invalid if used in actual scripts.

WordOpcodeHexDescriptionOP_PUBKEYHASH2530xfdRepresents a public key hashed with OP_HASH160.OP_PUBKEY2540xfeRepresents a public key compatible with OP_CHECKSIG.OP_INVALIDOPCODE2550xffMatches any opcode that is not yet assigned.

Reserved words

Any opcode not assigned is also reserved. Using an unassigned opcode makes the transaction invalid.

WordOpcodeHexWhen used...OP_RESERVED800x50Transaction is invalid unless occuring in an unexecuted OP_IF branchOP_VER980x62Transaction is invalid unless occuring in an unexecuted OP_IF branchOP_VERIF1010x65Transaction is invalid even when occuring in an unexecuted OP_IF branchOP_VERNOTIF1020x66Transaction is invalid even when occuring in an unexecuted OP_IF branchOP_RESERVED11370x89Transaction is invalid unless occuring in an unexecuted OP_IF branchOP_RESERVED21380x8aTransaction is invalid unless occuring in an unexecuted OP_IF branchOP_NOP1-OP_NOP10176-1850xb0-0xb9The word is ignored. Does not mark transaction as invalid.

Scripts

This is a list of interesting scripts. Keep in mind that all constants actually use the data-pushing commands above. Note that there is a small number of standard script forms that are relayed from node to node; non-standard scripts are accepted if they are in a block, but nodes will not relay them.

Standard Transaction to Bitcoin address (pay-to-pubkey-hash)

scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIGscriptSig: <sig> <pubKey>

To demonstrate how scripts look on the wire, here is a raw scriptPubKey:

  76       A9             14OP_DUP OP_HASH160    Bytes to push89 AB CD EF AB BA AB BA AB BA AB BA AB BA AB BA AB BA AB BA   88         AC                      Data to push                     OP_EQUALVERIFY OP_CHECKSIG

Note: scriptSig is in the input of the spending transaction and scriptPubKey is in the output of the previously unspent i.e. "available" transaction.

Here is how each word is processed:

StackScriptDescriptionEmpty.<sig> <pubKey> OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIGscriptSig and scriptPubKey are combined.<sig> <pubKey>OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIGConstants are added to the stack.<sig> <pubKey> <pubKey>OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIGTop stack item is duplicated.<sig> <pubKey> <pubHashA><pubKeyHash> OP_EQUALVERIFY OP_CHECKSIGTop stack item is hashed.<sig> <pubKey> <pubHashA> <pubKeyHash>OP_EQUALVERIFY OP_CHECKSIGConstant added.<sig> <pubKey>OP_CHECKSIGEquality is checked between the top two stack items.trueEmpty.Signature is checked for top two stack items.

Standard Generation Transaction (pay-to-pubkey)

OP_CHECKSIG is used directly without first hashing the public key. By default the reference implementation uses this form for coinbase payment, and scriptPubKeys of this transaction form are recognized as payments to user. The disadvantage of this transaction form is that the whole public key needs to be known in advance, implying longer payment addresses, and that it provides less protection in the event of a break in the ECDSA signature algorithm.

scriptPubKey: <pubKey> OP_CHECKSIGscriptSig: <sig>

Checking process:

StackScriptDescriptionEmpty.<sig> <pubKey> OP_CHECKSIGscriptSig and scriptPubKey are combined.<sig> <pubKey>OP_CHECKSIGConstants are added to the stack.trueEmpty.Signature is checked for top two stack items.

Provably Unspendable/Prunable Outputs

The standard way to mark a transaction as provably unspendable is with a scriptPubKey of the following form:

 scriptPubKey: OP_RETURN {zero or more ops}

OP_RETURN immediately marks the script as invalid, guaranteeing that no scriptSig exists that could possibly spend that output. Thus the output can be immediately pruned from the UTXO set even if it has not been spent. eb31ca1a4cbd97c2770983164d7560d2d03276ae1aee26f12d7c2c6424252f29 is an example: it has a single output of zero value, thus giving the full 0.125BTC fee to the miner who mined the transaction without adding an entry to the UTXO set. You can also use OP_RETURN to add data to a transaction without the data ever appearing in the UTXO set, as seen in 1a2e22a717d626fc5db363582007c46924ae6b28319f07cb1b907776bd8293fc; P2Pool does this with the share chain hash txout in the coinbase of blocks it creates.

Note that this mechanism is not yet a standard transaction type, and thus will not be relayed by nodes on mainnet.

Anyone-Can-Spend Outputs

Conversely a transaction can be made spendable by anyone at all:

 scriptPubKey: (empty) scriptSig: OP_TRUE

With some software changes such transactions can be used as a way to donate funds to miners in addition to transaction fees: any miner who mines such a transaction can also include an additional one after it sending the funds to an address they control. This mechanism may be used in the future for fidelity bonds to sacrifice funds in a provable way.

Anyone-Can-Spend outputs are currently considered non-standard, and are not relayed on the P2P network.

Transaction puzzle

Transaction a4bfa8ab6435ae5f25dae9d89e4eb67dfa94283ca751f393c1ddc5a837bbc31b is an interesting puzzle.

scriptPubKey: OP_HASH256 6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000 OP_EQUALscriptSig: 

To spend the transaction you need to come up with some data such that hashing the data twice results in the given hash.

StackScriptDescriptionEmpty.<data> OP_HASH256 <given_hash> OP_EQUAL <data>OP_HASH256 <given_hash> OP_EQUALscriptSig added to the stack.<data_hash><given_hash> OP_EQUALThe data is hashed.<data_hash> <given_hash>OP_EQUALThe given hash is pushed to the stack.trueEmpty.The hashes are compared, leaving true on the stack.

This transaction was successfully spent by 09f691b2263260e71f363d1db51ff3100d285956a40cc0e4f8c8c2c4a80559b1. The required data happened to be the Genesis block, and the given hash was the genesis block hash. Note that while transactions like this are fun, they are not secure, because they do not contain any signatures and thus any transaction attempting to spend them can be replaced with a different transaction sending the funds somewhere else.


0 0