### Multisig Script Assembly Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0021-ckb-address-format/0021-ckb-address-format.md This example shows how to assemble a multisig script for the 'args' field in the short payload format. It specifies the format version, required signatures, and public keys. ```c S | R | M | N | blake160(Pubkey1) | blake160(Pubkey2) | ... ``` -------------------------------- ### Transition from DEFINED to STARTED state Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0043-ckb-softfork-activation/0043-ckb-softfork-activation.md In the DEFINED state, transitions to STARTED if the current epoch number reaches or exceeds the specified start epoch. ```rust match state { ThresholdState::DEFINED => { if epoch.number() >= start { next_state = ThresholdState::STARTED; } } ``` -------------------------------- ### Molecule `byte` Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md A single byte is represented directly. Example shows '00'. ```text 00 ``` -------------------------------- ### Transition from STARTED to LOCKED_IN or FAILED state Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0043-ckb-softfork-activation/0043-ckb-softfork-activation.md In the STARTED state, counts blocks within a period that have the deployment bit set. Transitions to LOCKED_IN if the threshold is met, or to FAILED if the timeout epoch is reached. ```rust match state { ThresholdState::STARTED => { let mut count = 0; for block in (0..period_blocks) { if (block.version() & 0xE0000000 == 0x00000000 && (block.version() >> bit) & 1 == 1) { ++count; } } let threshold_number = threshold_number(period_blocks, threshold); if count >= threshold_number { next_state = ThresholdState::LOCKED_IN; } else if epoch_ext.number() >= timeout { next_state = ThresholdState::FAILED; } } ``` -------------------------------- ### Python Example for Compact Target Conversion Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0027-block-structure/0027-block-structure.md Provides Python 3 functions to convert between compact target format and target values, along with unit tests. Useful for understanding and implementing difficulty adjustments. ```python import unittest def compact_to_target(compact): exponent = compact >> 24 mantissa = compact & 0x00ffffff rtn = 0 if (exponent <= 3): mantissa >>= (8 * (3 - exponent)) rtn = mantissa else: rtn = mantissa rtn <<= (8 * (exponent - 3)) overflow = mantissa != 0 and (exponent > 32) return rtn, overflow def target_to_compact(target): bits = (target).bit_length() exponent = ((bits + 7) // 8) compact = target << ( 8 * (3 - exponent)) if exponent <= 3 else (target >> (8 * (exponent - 3))) compact = (compact | (exponent << 24)) return compact class TestCompactTarget(unittest.TestCase): def test_compact_target1(self): compact = target_to_compact(0x2) self.assertEqual('0x1020000', hex(compact)) target, overflow = compact_to_target(0x1020000) self.assertTupleEqual((2, False), (target, overflow)) def test_compact_target2(self): compact = target_to_compact(0xfe) self.assertEqual('0x1fe0000', hex(compact)) target, overflow = compact_to_target(0x1fedcba) self.assertTupleEqual((0xfe, False), (target, overflow)) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### CKB VM Contract Execution Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0003-ckb-vm/0003-ckb-vm.md Illustrates a basic CKB VM contract's main function, demonstrating how to load input and output cells using ckb_load_cell syscalls. This pattern is common for contracts that need to process transaction data. ```c int main(int argc, char* argv[]) { uint64_t input_cell_length = 10000; void *input_cell = malloc(input_cell_length); ckb_load_cell(input_cell, &input_cell_length, 0, 0, CKB_SOURCE_INPUT); uint64_t output_cell_length = 10000; void *output_cell = malloc(output_cell_length); ckb_load_cell(output_cell, &output_cell_length, 0, 0, CKB_SOURCE_OUTPUT); // Consume input & output cell return 0; } ``` -------------------------------- ### Example: Multiple Data Hash Matches Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0029-allow-script-multiple-matches-on-identical-code/0029-allow-script-multiple-matches-on-identical-code.md Demonstrates multiple matches on data hash, which is permissible under both the old and new consensus rules as data hash directly refers to the code. ```yaml # hash(Cell B.data) equals to hash(Cell A.data) cell_deps: - out_point: ... # Expands to # - out_point: Cell A dep_group: DepGroup - out_point: ... # Expands to # - out_point: Cell B dep_group: DepGroup inputs: - out_point: ... lock: code_hash: hash(Cell A.data) hash_type: Data ``` -------------------------------- ### Create an Anyone-Can-Pay Cell Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0026-anyone-can-pay/0026-anyone-can-pay.md This example shows how to create a new cell with an Anyone-Can-Pay lock. It specifies the capacity, type script, lock script arguments (including minimum CKB and UDT transfer amounts), and initial data. A valid signature for the owner is required in the witnesses. ```text Inputs: Normal Cell: Capacity: 1000 CKBytes Lock: code_hash: secp256k1_blake2b lock args: Outputs: Anyone-can-pay Cell: Capacity: 999.99 CKBytes Type: code_hash: simple udt lock args: Lock: code_hash: anyone-can-pay lock args: Data: Amount: 0 UDT Witnesses: ``` -------------------------------- ### Molecule `array` of `Uint32` Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializing a 32-bit unsigned integer '0x01020304' in little-endian into a byte array results in '04 03 02 01'. ```text 04 03 02 01 ``` -------------------------------- ### Unlock via CKByte Payment With Minimums Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0026-anyone-can-pay/0026-anyone-can-pay.md This example demonstrates the structure of inputs, outputs, and witnesses for a transaction utilizing the Anyone Can Pay cell with minimum CKByte and UDT requirements. It shows how a deposit cell and an ACP cell are processed, including the capacity and data amounts for both CKBytes and UDTs. ```plaintext Inputs: Deposit Normal Cell: Capacity: 500 CKBytes Lock: code_hash: secp256k1_blake2b lock args: Type: code_hash: simple udt lock args: Data: Amount: 200000 UDT Anyone-can-pay Cell: Capacity: 1000 CKBytes Lock: code_hash: anyone-can-pay lock args: Type: code_hash: simple udt lock args: Data: Amount: 3000 UDT Outputs: Deposit Change Cell: Capacity: 489.99 CKBytes Lock: code_hash: secp256k1_blake2b lock args: Type: code_hash: simple udt lock args: Data: Amount: 200000 UDT Anyone-can-pay Cell: Capacity: 1010 CKBytes Lock: code_hash: anyone-can-pay lock args: Type: code_hash: simple udt lock args: Data: Amount: 3000 UDT Witnesses: ``` -------------------------------- ### Example: Multiple Type Script Hash Matches (Same Cell) Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0029-allow-script-multiple-matches-on-identical-code/0029-allow-script-multiple-matches-on-identical-code.md Illustrates a scenario where multiple type script hash matches in cell dependencies effectively point to the same underlying cell, which is valid under the proposed rule. ```yaml # An example that multiple matches on the type script hash really are the same cell. cell_deps: - out_point: ... # Expands to # - out_point: Cell A dep_group: DepGroup - out_point: ... # Expands to # - out_point: Cell A dep_group: DepGroup inputs: - out_point: ... lock: ... type: code_hash: hash(Cell A.type) hash_type: Type ``` -------------------------------- ### Get VM Version Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0034-vm-syscalls-2/0034-vm-syscalls-2.md Retrieves the current running VM version. Returns an error code for Lina CKB-VM or 1 for the new hardfork version. Consumes 500 cycles. ```c int ckb_vm_version() { return syscall(2041, 0, 0, 0, 0, 0, 0); } ``` -------------------------------- ### Example: Multiple Type Script Hash Matches (Same Code) Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0029-allow-script-multiple-matches-on-identical-code/0029-allow-script-multiple-matches-on-identical-code.md Shows a transaction that is invalid under the old rule but valid under the new rule, where multiple type script hash matches resolve to the same script code. ```yaml # hash(Cell B.data) equals to hash(Cell A.data) # and hash(Cell B.type) equals to hash(Cell A.type) cell_deps: - out_point: ... # Expands to # - out_point: Cell A dep_group: DepGroup - out_point: ... # Expands to # - out_point: Cell B dep_group: DepGroup inputs: - out_point: ... lock: ... type: code_hash: hash(Cell A.type) hash_type: Type ``` -------------------------------- ### Molecule `array` of `byte` Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializing an array of three bytes '01', '02', '03' results in their direct concatenation. ```text 01 02 03 ``` -------------------------------- ### Molecule `array` of `Uint32` Array Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializing an array containing two 32-bit unsigned integers ('0x01020304' and '0xabcde') in little-endian. ```text 04 03 02 01 de bc 0a 00 ``` -------------------------------- ### Callee: Receive and Echo Data Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0050-vm-syscalls-3/0050-vm-syscalls-3.md This C code represents a spawned process that reads data from its standard input and writes it to its standard output. It uses `ckb_inherited_file_descriptors` to get the file descriptors for stdin and stdout, then `ckb_read_all` and `ckb_write` to echo the data. ```c #include #include #include "ckb_syscalls.h" #define CKB_STDIN (0) #define CKB_STDOUT (1) // Function read_all reads from fd until an error or EOF and returns the data it read. int ckb_read_all(uint64_t fd, void* buffer, size_t* length) { int err = 0; size_t read_length = 0; size_t full_length = *length; uint8_t* b = buffer; while (true) { size_t n = full_length - read_length; err = ckb_read(fd, b, &n); if (err == CKB_OTHER_END_CLOSED) { err = 0; *length = read_length; break; } else { if (err != 0) { goto exit; } } if (full_length - read_length == 0) { err = CKB_LENGTH_NOT_ENOUGH; if (err != 0) { goto exit; } } b += n; read_length += n; *length = read_length; } exit: return err; } int main() { int err = 0; uint64_t fds[2] = {0}; uint64_t fds_len = 2; err = ckb_inherited_file_descriptors(fds, &fds_len); if (err != 0) { goto exit; } uint8_t buffer[1024] = {0}; size_t length; length = 1024; err = ckb_read_all(fds[CKB_STDIN], buffer, &length); if (err != 0) { goto exit; } err = ckb_write(fds[CKB_STDOUT], buffer, &length); if (err != 0) { goto exit; } err = ckb_close(fds[CKB_STDOUT]); if (err != 0) { goto exit; } exit: return err; } ``` -------------------------------- ### Compile and Run C Reference Implementation Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0010-eaglesong/0010-eaglesong.md Instructions for compiling the C reference implementation using GCC and running the executable to hash input from stdin. ```bash $> gcc -o hash eaglesong.c hash.c $> ./hash > Hello, world! > [Ctrl-D] > 64867e2441d162615dc2430b6bcb4d3f4b95e4d0db529fca1eece73c077d72d6 ``` -------------------------------- ### Run Python Reference Implementation Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0010-eaglesong/0010-eaglesong.md Instructions for running the Python reference implementation to hash input from stdin. ```bash $> python hash.py > Hello, world! > [Ctrl-D] > 64867e2441d162615dc2430b6bcb4d3f4b95e4d0db529fca1eece73c077d72d6 ``` -------------------------------- ### Get Current Cycles Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0034-vm-syscalls-2/0034-vm-syscalls-2.md Returns the current cycle consumption just before executing the syscall. Consumes 500 cycles. ```c uint64_t ckb_current_cycles() { return syscall(2042, 0, 0, 0, 0, 0, 0); } ``` -------------------------------- ### Molecule `struct` with `byte` Field Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializing a struct containing a single byte field with value 'ab'. ```text ab ``` -------------------------------- ### Caller: Spawn Process and Redirect I/O Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0050-vm-syscalls-3/0050-vm-syscalls-3.md This C code demonstrates how to spawn a new process using `ckb_spawn` and redirect its standard input and output. It sets up pipes for communication, writes data to the spawned process's stdout, and reads data back from its stdin. ```c #include #include #include "ckb_syscalls.h" #define CKB_STDIN (0) #define CKB_STDOUT (1) // Function read_all reads from fd until an error or EOF and returns the data it read. int ckb_read_all(uint64_t fd, void* buffer, size_t* length) { int err = 0; size_t read_length = 0; size_t full_length = *length; uint8_t* b = buffer; while (true) { size_t n = full_length - read_length; err = ckb_read(fd, b, &n); if (err == CKB_OTHER_END_CLOSED) { err = 0; *length = read_length; break; } else { if (err != 0) { goto exit; } } if (full_length - read_length == 0) { err = CKB_LENGTH_NOT_ENOUGH; if (err != 0) { goto exit; } } b += n; read_length += n; *length = read_length; } exit: return err; } // Mimic stdio fds on linux int create_std_fds(uint64_t* fds, uint64_t* inherited_fds) { int err = 0; uint64_t to_child[2] = {0}; uint64_t to_parent[2] = {0}; err = ckb_pipe(to_child); if (err != 0) { goto exit; } err = ckb_pipe(to_parent); if (err != 0) { goto exit; } inherited_fds[0] = to_child[0]; inherited_fds[1] = to_parent[1]; inherited_fds[2] = 0; fds[CKB_STDIN] = to_parent[0]; fds[CKB_STDOUT] = to_child[1]; exit: return err; } int main() { int err = 0; const char* argv[] = {}; uint64_t pid = 0; uint64_t fds[2] = {0}; // it must be end with zero uint64_t inherited_fds[3] = {0}; err = create_std_fds(fds, inherited_fds); if (err != 0) { goto exit; } spawn_args_t spgs = { .argc = 0, .argv = argv, .process_id = &pid, .inherited_fds = inherited_fds, }; err = ckb_spawn(0, 3, 0, 0, &spgs); if (err != 0) { goto exit; } size_t length = 0; length = 12; err = ckb_write(fds[CKB_STDOUT], "Hello World!", &length); if (err != 0) { goto exit; } err = ckb_close(fds[CKB_STDOUT]); if (err != 0) { goto exit; } uint8_t buffer[1024] = {0}; length = 1024; err = ckb_read_all(fds[CKB_STDIN], buffer, &length); if (err != 0) { goto exit; } err = memcmp("Hello World!", buffer, length); if (err != 0) { goto exit; } exit: return err; } ``` -------------------------------- ### Build Simple UDT Script Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0025-simple-udt/0025-simple-udt.md Clone the ckb-production-scripts repository, checkout a specific commit, initialize submodules, and build the Simple UDT script using Docker. This process allows for reproducible builds to verify the deployed script. ```bash $ git clone https://github.com/nervosnetwork/ckb-production-scripts $ cd ckb-production-scripts $ git checkout e570c11aff3eca12a47237c21598429088c610d5 $ git submodule update --init --recursive $ make all-via-docker ``` -------------------------------- ### Cell Data Structure Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0019-data-structures/0019-data-structures.md A JSON representation of a Cell, illustrating its capacity, lock script, and optional type script. ```json { "capacity": "0x19995d0ccf", "lock": { "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", "args": "0x0a486fb8f6fe60f76f001d6372da41be91172259", "hash_type": "type" }, "type": null } ``` -------------------------------- ### Build Anyone Can Pay Lock Script with Docker Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0026-anyone-can-pay/0026-anyone-can-pay.md Steps to clone the ckb-production-scripts repository, checkout a specific commit, initialize submodules, and build the Anyone Can Pay lock script using Docker for reproducible builds. ```bash $ git clone https://github.com/nervosnetwork/ckb-production-scripts $ cd ckb-production-scripts $ git checkout e570c11aff3eca12a47237c21598429088c610d5 $ git submodule update --init $ make all-via-docker ``` -------------------------------- ### GetBlockFilterHashes Message Structure Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0045-client-block-filter/0045-client-block-filter.md Structure for requesting verifiable filter hashes for a given range of blocks. Requires the starting block number. ```rust struct GetBlockFilterHashes { start_number: Uint64, // The height of the first block in the requested range } ``` -------------------------------- ### Build Omnilock Script with Docker Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0042-omnilock/0042-omnilock.md Instructions to clone the Omnilock repository, checkout a specific commit, initialize submodules, and build the script using Docker for reproducible builds. ```bash $ git clone https://github.com/cryptape/omnilock.git $ cd omnilock $ git checkout cd764d $ git submodule update --init --recursive $ make all-via-docker ``` -------------------------------- ### GetBlockFilters Message Structure Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0045-client-block-filter/0045-client-block-filter.md Defines the structure for requesting compact filters of a specific block range. Requires the starting block number. ```rust struct GetBlockFilters { start_number: Uint64, // The height of the first block in the requested range } ``` -------------------------------- ### Main Function for Dynamic Linking in CKB VM Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0003-ckb-vm/0003-ckb-vm.md This C code demonstrates a main function within CKB VM that reads input and output cells, and dynamically calls UDT functions based on command-line arguments. It ensures that the input and output data structures are identical after execution. ```c int main(int argc, char* argv[]) { data_t *input_data = NULL; ret = ckb_read_cell(0, CKB_SOURCE_INPUT, (void **) &input_data, NULL); if (ret != 0) { return ret; } data_t *output_data = NULL; ret = ckb_read_cell(0, CKB_SOURCE_OUTPUT, (void **) &output_data, NULL); if (ret != 0) { return ret; } if (strcmp(argv[4], "initialize") == 0) { // processing initialize arguments ret = udt_initialize(...); if (ret != 0) { return ret; } } else if (strcmp(argv[4], "transfer") == 0) { // processing transfer arguments ret = udt_transfer(input_data, ...); if (ret != 0) { return ret; } } else if (strcmp(argv[4], "approve") == 0) { // processing approve arguments ret = udt_approve(input_data, ...); if (ret != 0) { return ret; } } // more commands here if (memcmp(input_data, output_data, sizeof(data_t)) != 0) { return -1; } return 0; } ``` -------------------------------- ### Get Current Process ID - ckb_process_id Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0050-vm-syscalls-3/0050-vm-syscalls-3.md Returns the Process ID of the currently executing process. The root process has an ID of 0. ```c uint64_t ckb_process_id(); ``` -------------------------------- ### GetBlockFilterCheckPoints Message Structure Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0045-client-block-filter/0045-client-block-filter.md Used to request filter hashes at regular intervals within a block range. Requires the starting block number. ```rust struct GetBlockFilterCheckPoints { start_number: Uint64, // The height of the first block in the requested range } ``` -------------------------------- ### Build Extensible UDT Script Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0052-extensible-udt/0052-extensible-udt.md Clone the ckb-production-scripts repository, checkout a specific commit, initialize submodules, and build the script using Docker. This ensures a reproducible build of the deployed script. ```bash $ git clone https://github.com/nervosnetwork/ckb-production-scripts $ cd ckb-production-scripts $ git checkout abdcb117b512e35910fa8e30241a7a354e5cacf0 $ git submodule update --init --recursive $ make all-via-docker ``` -------------------------------- ### Molecule `struct` with `byte` and `Uint32` Fields Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializing a struct with a byte field ('ab') and a 32-bit unsigned integer ('0x010203') in little-endian. ```text ab 03 02 01 00 ``` -------------------------------- ### Block Inclusion Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md This JSON object represents a block that includes the DAO deposit transaction. It contains block header information and the transaction root. ```json { "compact_target": "0x1a2dfb48", "hash": "0xba6eaa7e0acd0dc78072c5597ed464812391161f0560c35992ae0c96cd1d6073", "number": "0x11ea4", "parent_hash": "0x36f16c9a1abea1cb44bc1d923feb9f62ff45b9327188dca954968dfdecc03bd0", "nonce": "0x74e39f370400000000000000bb4b3299", "timestamp": "0x16ea78c300f", "transactions_root": "0x4efccc5beeeae3847aa65f2e987947957d68f13687af069f52be361d0648feb8", "proposals_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", "uncles_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", "version": "0x0", "epoch": "0x645017e00002f", "dao": "0x77a7c6ea619acb2e4b841a96c88e2300b6b274a096c1080000ea07db0efaff06" } ``` -------------------------------- ### Load Cell Data As Code Syscall Implementation Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0009-vm-syscalls/0009-vm-syscalls.md Implements the `ckb_load_cell_data_as_code` syscall for loading cell data into VM memory and marking it as executable. Use this for dynamic linking. ```c int ckb_load_cell_data_as_code(void* addr, size_t memory_size, size_t content_offset, size_t content_size, size_t index, size_t source) { return syscall(2091, addr, memory_size, content_offset, content_size, index, source); } ``` -------------------------------- ### Loading Headers via Header Deps Index Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md Demonstrates how to load block headers using their index within the `header_deps` array. This is useful for accessing specific block information required by scripts. ```c // Load the first block in header_deps, the block Hi load_header(..., 0, CKB_SOURCE_HEADER_DEP); ``` ```c // Load the second block in header_deps, the block Hj load_header(..., 1, CKB_SOURCE_HEADER_DEP); ``` -------------------------------- ### DAO Deposit Transaction Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md This JSON object represents a transaction that includes a DAO deposit cell. It details cell dependencies, inputs, outputs, and witness data. ```json { "version": "0x0", "cell_deps": [ { "out_point": { "tx_hash": "0x71a7ba8fc96349fea0ed3a5c47992e3b4084b031a42264a018e0072e8172e46c", "index": "0x0" }, "dep_type": "dep_group" }, { "out_point": { "tx_hash": "0xe2fb199810d49a4d8beec56718ba2593b665db9d52299a0f9e6e75416d73ff5c", "index": "0x2" }, "dep_type": "code" } ], "header_deps": [ "0x37ef8cf2407044d74a71f927a7e3dcd3be7fc5e7af0925c0b685ae3bedeec3bc" ], "inputs": [ { "previous_output": { "tx_hash": "0x81c400a761b0b5f1d8b00d8939e5a729d21d25a08e14e54f0661cb4f6fc6fb81", "index": "0x0" }, "since": "0x0" }, { "previous_output": { "tx_hash": "0x043639b6aedcd0d897583e3d056e5a9c4875538533733818aca31fbeabfd5fba", "index": "0x1" }, "since": "0x0" } ], "outputs": [ { "capacity": "0x2e90edd000", "lock": { "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", "args": "0xe5f99902495d04d9dcb013aefc96093d365b77dc", "hash_type": "type" }, "type": { "code_hash": "0x82d76d1b75fe2fd9a27dfbaa65a039221a380d76c926f378d3f81cf3e7e13f2e", "args": "0x", "hash_type": "type" } }, { "capacity": "0x179411d65", "lock": { "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", "args": "0x5df75f10330a05ec9f862dec9bb37b5e11171475", "hash_type": "type" }, "type": null } ], "outputs_data": [ "0x5f10000000000000", "0x" ], "witnesses": [ "0x5500000010000000550000005500000041000000d952a9b844fc441529dd310e49907cc5eba009dcf0fcd7a5fb1394017c29b90b7c68e1d0db52c67d444accec4c04670d197630656837b33d07f0cbdd1f33907d01", "0x5500000010000000550000005500000041000000d8e77676d57742b9b1e3a47e53f023ade294af5ca501f33406e992af01b1d0dd4a4f22d478c9497b184b04ea56c4ce71fccd9f0d4c25f503324edff5f2b26f0d00" ], "hash": "0x9ab05d622dc6d9816f70094242740cca594e677009b88c3f2b367d8b32f928fd" } ``` -------------------------------- ### Sponge Construction Pseudocode Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0010-eaglesong/0010-eaglesong.md Illustrates the absorbing and squeezing phases of the sponge construction algorithm. It takes input data and desired output length, processes the input through XORing chunks into the state and applying a permutation, then extracts the output. ```pseudocode function sponge( input, output_length ): // append delimiter and pad as necessary input = input || d while length(input) % r =/= 0 do: input = input || 0 // split for i in [0, length(input) / r] do: chunks[i] = input[i*r : (i+1)*r] // initialize state state = zeros(r+c) // absorb for chunk in chunks do: state[0:r] = state[0:r] xor chunk state = F(state) // squeeze output = "" while length(output) <= output_length do: output = output || state[0:r] state = F(state) return output[0:output_length] ``` -------------------------------- ### Always Exiting Lock Script Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md An example lock script that always exits normally, allowing any entity to destroy the cell it protects. This is useful for testing or simple scenarios. ```c int main(int argc, char *argv[]) { return 0; } ``` -------------------------------- ### UDT Data Structures Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0003-ckb-vm/0003-ckb-vm.md Defines the C data structures for storing UDT account information, including balances and allowed spending amounts. These structures are simplified for the example. ```c #define ADDRESS_LENGTH 32 #define MAX_BALANCES 100 #define MAX_ALLOWED 100 typedef struct { char address[ADDRESS_LENGTH]; int64_t tokens; } balance_t; typedef struct { char address[ADDRESS_LENGTH]; char spender[ADDRESS_LENGTH]; int64_t tokens; } allowed_t; typedef struct { balance_t balances[MAX_BALANCES]; int used_balance; allowed_t allowed[MAX_ALLOWED]; int used_allowed; char owner[ADDRESS_LENGTH]; char newOwner[ADDRESS_LENGTH]; int64_t total_supply; } data_t; ``` -------------------------------- ### CBMT Array Representation Examples Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0006-merkle-tree/0006-merkle-tree.md Illustrates the array representation of a CBMT for different numbers of items. The first element is node 0 (BO), the second is node 1, and so on. ```plaintext [B0, B1, B2, B3, B4, T0, T1, T2, T3, T4, T5] ``` ```plaintext [B0, B1, B2, B3, B4, B5, T0, T1, T2, T3, T4, T5, T6] ``` -------------------------------- ### Serialize None Option Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0008-serialization/0008-serialization.md Serializes an empty option. This results in zero bytes. ```option ``` -------------------------------- ### Transaction JSON Example Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0019-data-structures/0019-data-structures.md This JSON object represents a typical transaction structure. It includes fields like version, cell dependencies, header dependencies, inputs, outputs, output data, and witnesses. ```json { "version": "0x0", "cell_deps": [ { "out_point": { "tx_hash": "0xbd864a269201d7052d4eb3f753f49f7c68b8edc386afc8bb6ef3e15a05facca2", "index": "0x0" }, "dep_type": "dep_group" } ], "header_deps": [ "0xaa1124da6a230435298d83a12dd6c13f7d58caf7853f39cea8aad992ef88a422" ], "inputs": [ { "previous_output": { "tx_hash": "0x8389eba3ae414fb6a3019aa47583e9be36d096c55ab2e00ec49bdb012c24844d", "index": "0x1" }, "since": "0x0" } ], "outputs": [ { "capacity": "0x746a528800", "lock": { "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", "args": "0x56008385085341a6ed68decfabb3ba1f3eea7b68", "hash_type": "type" }, "type": null }, { "capacity": "0x1561d9307e88", "lock": { "code_hash": "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", "args": "0x886d23a7858f12ebf924baaacd774a5e2cf81132", "hash_type": "type" }, "type": null } ], "outputs_data": [ "0x", "0x" ], "witnesses": [ "0x55000000100000005500000055000000410000004a975e08ff99fa000142ff3b86a836b43884b5b46f91b149f7cc5300e8607e633b7a29c94dc01c6616a12f62e74a1415f57fcc5a00e41ac2d7034e90edf4fdf800" ] } ``` -------------------------------- ### CKB Load Script Syscall Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0022-transaction-structure/0022-transaction-structure.md Demonstrates the `ckb_load_script` syscall, used within a CKB script to load its own code. The arguments specify the destination buffer, maximum length, and offset for reading. ```c ckb_load_script(addr, len, offset) ``` -------------------------------- ### GetLastStateProof Message Structure Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/0044-ckb-light-client.md A client's request for a proof of the last state known to the client. It specifies the client's known block hash, start block details, and criteria for block inclusion in the proof. ```molecule table GetLastStateProof { // The last block hash known by the client. // It could be different with the tip hash in the server. last_hash: Byte32, // The hash of the last proved block. start_hash: Byte32, // The block number of the last proved block. start_number: Uint64, // How many continuous blocks before the tip block should be included at // least, if possible? last_n_blocks: Uint64, // All blocks, whose total difficulty is not less than this difficulty // boundary, should be included in the proof. difficulty_boundary: Uint256, // The sampled difficulties. difficulties: Uint256Vec, } ``` -------------------------------- ### CKB Load Script Syscall Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0009-vm-syscalls/0009-vm-syscalls.md Loads the current running script into VM memory using Molecule Encoding. Follows the partial loading workflow. ```c int ckb_load_script(void* addr, uint64_t* len, size_t offset) { return syscall(2052, addr, len, offset, 0, 0, 0); } ``` -------------------------------- ### Unlock Anyone-Can-Pay Cell via CKB Payment Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0026-anyone-can-pay/0026-anyone-can-pay.md This example shows how an Anyone-Can-Pay cell can be unlocked without a direct signature if a sufficient amount of CKB is deposited into it. This bypasses the typical 61 CKBytes minimum requirement for plain transfers. ```text Inputs: Deposit Normal Cell: Capacity: 500 CKBytes Lock: code_hash: secp256k1_blake2b lock args: Anyone-can-pay Cell: Capacity: 1000 CKBytes Lock: code_hash: anyone-can-pay lock args: Outputs: Deposit Change Cell: Capacity: 479.99 CKBytes Lock: code_hash: secp256k1_blake2b lock args: Anyone-can-pay Cell: Capacity: 1020 CKBytes Lock: code_hash: anyone-can-pay lock args: Witnesses: ``` -------------------------------- ### Spawn Arguments Structure Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0050-vm-syscalls-3/0050-vm-syscalls-3.md Defines the structure for arguments passed to the `ckb_spawn` syscall, including argument count, argument values, a pointer for the child process ID, and inherited file descriptors. ```c typedef struct spawn_args_t { size_t argc; const char** argv; /* Spawned VM process ID */ uint64_t* process_id; /* A list of file descriptor, 0 indicates end of array */ const uint64_t* inherited_fds; } spawn_args_t; ``` -------------------------------- ### Execute a File from Cell Data Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0034-vm-syscalls-2/0034-vm-syscalls-2.md Runs an executable file from specified cell data, replacing the current VM's code, registers, and memory. Cycle consumption includes a fixed 500 cycles plus initial loading cycles. ```c int ckb_exec(size_t index, size_t source, size_t place, size_t bounds, int argc, char* argv[]) { return syscall(2043, index, source, place, bounds, argc, argv); } ``` -------------------------------- ### Exec Syscall Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0034-vm-syscalls-2/0034-vm-syscalls-2.md Runs an executable file from specified cell data, replacing the current VM's code, registers, and memory. Cycle consumption includes a fixed 500 cycles plus initial loading cycles. ```APIDOC ## Exec Syscall ### Description Runs an executable file from specified cell data, replacing the current VM's code, registers, and memory. Cycle consumption includes a fixed 500 cycles plus initial loading cycles. ### Signature ```c int ckb_exec(size_t index, size_t source, size_t place, size_t bounds, int argc, char* argv[]) ``` ### Arguments - **index** (size_t): An index value denoting the index of entries to read. - **source** (size_t): A flag denoting the source of cells or witnesses to locate. Possible values include: - 1: input cells. - `0x0100000000000001`: input cells with the same running script as current script - 2: output cells. - `0x0100000000000002`: output cells with the same running script as current script - 3: dep cells. - **place** (size_t): A value of 0 or 1: - 0: read from cell data - 1: read from witness - **bounds** (size_t): High 32 bits means `offset`, low 32 bits means `length`. If `length` equals zero, it reads to the end instead of reading 0 bytes. - **argc** (int): The number of arguments passed to the program. - **argv** (char*[]): A one-dimensional array of strings. ### Cycles Consumed - Fixed 500 cycles - Initial Loading Cycles ``` -------------------------------- ### Load Cell Data Syscall Implementation Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0009-vm-syscalls/0009-vm-syscalls.md Implements the `ckb_load_cell_data` syscall for loading cell data into VM memory. Use this to read cell data content. ```c int ckb_load_cell_data(void* addr, uint64_t* len, size_t offset, size_t index, size_t source) { return syscall(2092, addr, len, offset, index, source, 0); } ``` -------------------------------- ### Build Cheque Lock Script Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0039-cheque/0039-cheque.md Steps to clone the repository, checkout a specific commit, update submodules, and build the Cheque Lock script using make and capsule. ```bash git clone https://github.com/nervosnetwork/ckb-Cheque-script cd ckb-Cheque-script git checkout 4ca3e62ae39c32cfcc061905515a2856cad03fd8 git submodule update --init cd contracts/ckb-Cheque-script/ckb-lib-secp256k1/ckb-production-scripts git submodule update --init cd .. && make all-via-docker cd ../../.. && capsule build --release ``` -------------------------------- ### Claim Cheque via Receiver Signature Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0039-cheque/0039-cheque.md This example demonstrates claiming UDT tokens from a Cheque cell using the receiver's signature. The receiver's signature unlocks the Cheque cell, and the tokens are transferred to a new SUDT cell. The original Cheque cell's capacity is returned to the sender. ```yaml inputs: cheque_cell: capacity: 165 CKBytes lock: code_hash: args: <20-byte_receiver_lock_hash> <20-byte_sender_lock_hash> type: data: sudt_amount: 100 UDT sudt_cell: capacity: 200 CKBytes lock: type: data: sudt_amount: 200 UDT outputs: sudt_cell: capacity: 199.99 CKBytes lock: type: data: sudt_amount: 300 UDT basic_cell: capacity: 165 CKBytes lock: witnesses: ``` -------------------------------- ### ckb_load_script_hash Syscall Signature in C Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0009-vm-syscalls/0009-vm-syscalls.md Presents the C function signature for the ckb_load_script_hash syscall, used to fetch the hash of the currently executing script. It supports partial loading. ```c int ckb_load_script_hash(void* addr, uint64_t* len, size_t offset) { return syscall(2062, addr, len, offset, 0, 0, 0); } ``` -------------------------------- ### Merkle Proof Generation Algorithm Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0006-merkle-tree/0006-merkle-tree.md C++ implementation for generating a Merkle proof. It identifies necessary sibling nodes and their corresponding indexes, sorting them as required. ```c++ Proof gen_proof(Hash tree[], U32 indexes[]) { Hash nodes[]; U32 tree_indexes[]; Queue queue; int size = len(tree) >> 1 + 1; indexes.desending_sort(); for index in indexes { queue.push_back(index + size - 1); } while(queue is not empty) { int index = queue.pop_front(); int sibling = calculate_sibling(index); if(sibling == queue.front()) { queue.pop_front(); } else { nodes.push_back(tree[sibling]); } int parent = calculate_parent(index); if(parent != 0) { queue.push_back(parent); } } add (size-1) for every index in indexes; sort indexes in ascending order by corresponding hash; return Proof::new(indexes, nodes); } ``` -------------------------------- ### Minimal C Contract for CKB VM Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0003-ckb-vm/0003-ckb-vm.md This is a minimal C contract that returns 0, demonstrating the intrinsic cost of the RISC-V model within the CKB VM. It can be significantly compressed. ```c int main() { return 0; } ``` -------------------------------- ### CKB Load Witness Syscall Source: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0009-vm-syscalls/0009-vm-syscalls.md Loads a witness entry from the current transaction based on source and index. Use this to access witness data for input or output cells, including those matching the current script. ```c int ckb_load_witness(void* addr, uint64_t* len, size_t offset, size_t index, size_t source) { return syscall(2074, addr, len, offset, index, source, 0); } ```