Black Friday ~40% off Growth and Pro annual plans See offers
  • Agents
  • Pricing

Sui transaction signing: from PTB to signed bytes

Created Nov 23, 2026 Updated Nov 23, 2026
Sui Transaction Signing logo

In Part 4, we built a programmable transaction block that created a notebook, changed its value to 42, checked that value, and transferred the notebook and its editing capability to Bob. We followed the inputs and return values through the program.

There is still a step hidden inside the command that submitted it. Alice’s wallet had to authorize that entire request. What data did it sign? Where does 42 appear in that data? And is the hash we sign the same one we later search for in the explorer?

In this blog post, we’ll retain the transaction before signing, decode its bytes with Python, and reconstruct the hash passed to an Ed25519 signer. Then we’ll change one byte, test the original signature against the changed request, and submit the original bytes to Testnet.

From a PTB to a signable request

A wallet needs a precise representation of the request it authorizes. Function names and a list of values are only part of that request. The transaction also identifies its sender, gas payer, gas price, budget, and expiration. Changing Bob’s address or the gas budget changes what Alice is being asked to approve.

Sui represents these fields in TransactionData. The PTB is nested inside its transaction kind. The client serializes the complete value into bytes, and authentication accompanies those bytes when the request is submitted. Here is the structure for our example.

TransactionData::V1
  kind = ProgrammableTransaction
    inputs
      Input(0) = 7
      Input(1) = 42
      Input(2) = Bob's address
    commands
      0 create(Input(0)) -> Notebook, EditCap
      1 set_value(NestedResult(0, 0), NestedResult(0, 1), Input(1))
      2 assert_value(NestedResult(0, 0), Input(1))
      3 TransferObjects([NestedResult(0, 0), NestedResult(0, 1)], Input(2))
  sender
  gas_data
  expiration

As a reminder, NestedResult(0, 1) selects the second value returned by command 0, our EditCap. These references belong to the program being signed. A later command cannot silently substitute a different object or recipient after Alice has authorized the bytes. The field order comes from Sui’s TransactionData definition.

Prepare the same notebook workflow

Keep the pinned CLI for this walkthrough because its JSON and binary schema are what our decoder checks. The binaries are available in the official release.

Start in a fresh directory and keep the same shell open for the variables used below.

Run

mkdir sui-signing-lab
cd sui-signing-lab
mkdir -p client evidence
sui --version
python3 --version
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install cryptography==46.0.3

Output, with installation progress omitted

sui 1.83.0-16d2dc1e05ed
Python 3.13.7
Successfully installed cffi-2.1.1 cryptography-46.0.3 pycparser-3.12

Use the disposable Testnet accounts alice and bob from Part 4, or create them with the two new-address commands below. Skip creation for an alias you already have. Alice pays for publication and the notebook transaction, while Bob only receives objects. Keep any recovery phrases printed during account creation private.

sui client --yes envs
sui client switch --env testnet

sui client new-address ed25519 alice
sui client new-address ed25519 bob
sui client switch --address bob

BOB=$(sui client active-address)
sui client switch --address alice

ALICE=$(sui client active-address)
sui client chain-identifier --json

sui client faucet --address "$ALICE"

Chain identifier from this run

{
  "base58": "69WiPg3DAQiwdxfncX6wYQ2siKwAe6L9BZthQea3JNMD",
  "hex": "4c78adac"
}

Check the chain identifier before proceeding. The faucet supplies Testnet SUI, and Alice’s local key remains in the CLI keystore. The public addresses and all transaction IDs printed in this post belong to the captured run. Your generated values will differ. If the faucet is rate limited, use its web interface.

We’ll publish the same Move module again so every command below uses a package produced by your own run. The constructor returns two objects, the setter checks the capability’s notebook ID, and the assertion checks the final value. These are the same functions we followed in Part 4.

sui move new --path move ptb_notebook

Replace move/Move.toml with this manifest. The pinned CLI supplies the standard framework dependencies.

[package]
name = "ptb_notebook"
edition = "2024"

Let’s create a file named move/sources/notebook.move.

module ptb_notebook::notebook;

const EWrongCapability: u64 = 1;
const EUnexpectedValue: u64 = 2;

public struct Notebook has key, store {
    id: UID,
    value: u64,
}

public struct EditCap has key, store {
    id: UID,
    notebook: ID,
}

public fun create(value: u64, ctx: &mut TxContext): (Notebook, EditCap) {
    let notebook = Notebook { id: object::new(ctx), value };
    let cap = EditCap {
        id: object::new(ctx),
        notebook: object::id(&notebook),
    };
    (notebook, cap)
}

public fun set_value(notebook: &mut Notebook, cap: &EditCap, value: u64) {
    assert!(cap.notebook == object::id(notebook), EWrongCapability);
    notebook.value = value;
}

public fun assert_value(notebook: &Notebook, expected: u64) {
    assert!(notebook.value == expected, EUnexpectedValue);
}

#[test]
fun create_update_and_check() {
    let ctx = &mut tx_context::dummy();
    let (mut notebook, cap) = create(7, ctx);
    set_value(&mut notebook, &cap, 42);
    assert_value(&notebook, 42);
    transfer::public_transfer(notebook, @0xB);
    transfer::public_transfer(cap, @0xB);
}

#[test, expected_failure(abort_code = EWrongCapability)]
fun reject_another_notebooks_capability() {
    let ctx = &mut tx_context::dummy();
    let (mut first, first_cap) = create(7, ctx);
    let (second, second_cap) = create(8, ctx);
    set_value(&mut first, &second_cap, 42);
    transfer::public_transfer(first, @0xB);
    transfer::public_transfer(first_cap, @0xB);
    transfer::public_transfer(second, @0xB);
    transfer::public_transfer(second_cap, @0xB);
}

#[test, expected_failure(abort_code = EUnexpectedValue)]
fun reject_an_unexpected_value() {
    let ctx = &mut tx_context::dummy();
    let (notebook, cap) = create(7, ctx);
    assert_value(&notebook, 8);
    transfer::public_transfer(notebook, @0xB);
    transfer::public_transfer(cap, @0xB);
}

Run

sui move test --path move

Output

INCLUDING DEPENDENCY MoveStdlib
INCLUDING DEPENDENCY Sui
BUILDING ptb_notebook
Running Move unit tests
[ PASS    ] ptb_notebook::notebook::create_update_and_check
[ PASS    ] ptb_notebook::notebook::reject_an_unexpected_value
[ PASS    ] ptb_notebook::notebook::reject_another_notebooks_capability
Test result: OK. Total tests: 3; passed: 3; failed: 0

The three tests cover the successful workflow and the two application assertions. The signing experiment below will use the successful four-command PTB.

We also need a small reader for saved CLI responses. It extracts public IDs for shell variables and prints the relevant parts of our receipts. This program reads JSON that the CLI has already decoded.

Let’s create a file named client/receipt.py.

import argparse
import json
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("path")
parser.add_argument("--field", choices=["package", "digest", "notebook", "signature"])
args = parser.parse_args()
data = json.loads(Path(args.path).read_text())

if args.field:
    if args.field == "package":
        print(next(c["packageId"] for c in data["objectChanges"] if c["type"] == "published"))
    elif args.field == "notebook":
        print(next(c["objectId"] for c in data["objectChanges"] if c["type"] == "created"
                   and c.get("objectType", "").endswith("::notebook::Notebook")))
    else:
        print(data["suiSignature" if args.field == "signature" else "digest"])
elif "result" in data:
    print("Native verification:", json.dumps(data["result"], sort_keys=True))
elif "effects" in data:
    print("Digest:", data["digest"])
    print("Status:", data["effects"]["status"]["status"])
    for c in data.get("objectChanges", []):
        if c["type"] == "published":
            print("Package:", c["packageId"])
        elif c["type"] == "created" and "::notebook::" in c.get("objectType", ""):
            print(c["objectType"].split("::")[-1] + ":", c["objectId"])
            print("Owner:", c["owner"]["AddressOwner"])
else:
    print("Notebook:", data["objectId"])
    print("Value:", data["content"]["value"])
    print("Version:", data["version"])
    print("Owner:", data["owner"]["AddressOwner"])

Run

sui client publish move --sender "$ALICE" --gas-budget 100000000 --json > evidence/publish.json
PACKAGE=$(python3 client/receipt.py evidence/publish.json --field package)
python3 client/receipt.py evidence/publish.json

Output

Digest: 6VCz6LvMv43MLsLbffXHPhF6kbCCEMZp74QHKMVJpPp4
Status: success
Package: 0x9f5b713d32b33f69b00663cf0dee268e39c4c0c5cdc4fc7c34db7ebe24f4bd4f

The published package supplies the code for our next transaction. The helper’s --field package mode prints only the package ID, which is why it can populate PACKAGE.

Now build the notebook PTB with --serialize-unsigned-transaction. Construction can query Testnet for information such as the gas price and validity range. The command returns the unsigned request as Base64 so we can save the exact bytes before signing.

Run

sui client ptb \
  --move-call "$PACKAGE::notebook::create" 7 \
  --assign created \
  --move-call "$PACKAGE::notebook::set_value" created.0 created.1 42 \
  --move-call "$PACKAGE::notebook::assert_value" created.0 42 \
  --transfer-objects "[created.0, created.1]" "@$BOB" \
  --sender "@$ALICE" --gas-budget 50000000 \
  --serialize-unsigned-transaction > evidence/unsigned.b64

TX_BYTES=$(cat evidence/unsigned.b64)
cat evidence/unsigned.b64

Output

AAADAAgHAAAAAAAAAAAIKgAAAAAAAAAAIBc99m7j2LiI3i56Wj+yrwLTys+LhNoz1hLyLpq87phIBACfW3E9MrM/abAGY88N7iaOOcTAxc3E/Hw0236+JPS9Twhub3RlYm9vawZjcmVhdGUAAQEAAACfW3E9MrM/abAGY88N7iaOOcTAxc3E/Hw0236+JPS9Twhub3RlYm9vawlzZXRfdmFsdWUAAwMAAAAAAwAAAQABAQAAn1txPTKzP2mwBmPPDe4mjjnEwMXNxPx8NNt+viT0vU8Ibm90ZWJvb2sMYXNzZXJ0X3ZhbHVlAAIDAAAAAAEBAAECAwAAAAADAAABAAECAJXrl5/nXsqYc19M1t1upJxzLgpKoT9cc/niDhW9FKimAJXrl5/nXsqYc19M1t1upJxzLgpKoT9cc/niDhW9FKim6AMAAAAAAACA8PoCAAAAAAIBCgUAAAAAAAABCwUAAAAAAAAAACBMeK2s8qL1rYDyftfVSqadOnjxymf9757PV1T1uLt3sMuS0og=

Base64 is a printable encoding of the binary data. Decoding it gives us 398 bytes in this run. Signing and later submitting the saved value will keep the request fixed. Calling the builder again could select new metadata, including a different validity nonce. Sui documents this separation between construction, signing, and submission in its offline signing flow.

Read the transaction as bytes

Sui uses Binary Canonical Serialization, or BCS, to encode TransactionData. A canonical encoding gives a value of a particular type one valid byte representation. The decoder still needs the schema. The bytes do not contain JSON field names or a type label beside every value.

Fixed-width integers use little-endian byte order. A u64 occupies eight bytes, so our value 42 becomes 2a00000000000000. Vectors and strings carry lengths. Enum values carry a variant index followed by the selected variant’s fields. Lengths and variant indexes use ULEB128, which uses seven payload bits per byte and a continuation bit when another byte follows. See the BCS specification.

The beginning of this transaction is small enough to read directly. The numbers below are hexadecimal bytes, and the labels explain their meaning under Sui’s schema.

00                         TransactionData variant 0 = V1
00                         TransactionKind variant 0 = ProgrammableTransaction
03                         input vector length = 3
00 08                      Pure variant 0, then a byte-vector length of 8
07 00 00 00 00 00 00 00    Input(0), interpreted by create as u64 7
00 08                      Pure variant 0, then a byte-vector length of 8
2a 00 00 00 00 00 00 00    Input(1), interpreted by the calls as u64 42
00 20                      Pure variant 0, then a byte-vector length of 32
...                        Input(2), Bob's 32-byte address

Notice that V1 is encoded with variant index 0. Its name does not determine its byte value. Also, the 00 08 before 42 describes a pure input containing eight bytes. Its interpretation as a u64 comes from the called Move functions.

The references from Part 4 have a binary representation too. Their enum tags and their indexes occupy separate parts of the encoding. The indexes here are fixed-width u16 values.

Input(1)          = 01 01 00
                    ^^ tag 1, followed by u16 input index 1

NestedResult(0, 1) = 03 00 00 01 00
                    ^^ tag 3, followed by u16 command 0 and u16 result 1

We can now implement a decoder for this notebook request. It supports pure inputs, our two command kinds, empty Move type arguments, gas payment references, and the expiration variants used here. It rejects other forms. A production decoder must cover the full supported schema and its validation limits. The relevant definitions are in Sui’s pinned transaction source.

Let’s create a file named client/decode_tx.py.

import argparse
import base64
import json
from pathlib import Path

ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def base58(data):
    number = int.from_bytes(data, "big")
    text = ""
    while number:
        number, digit = divmod(number, 58)
        text = ALPHABET[digit] + text
    return "1" * (len(data) - len(data.lstrip(b"\0"))) + text

class Reader:
    def __init__(self, data):
        self.data = data
        self.pos = 0
        self.spans = {}

    def take(self, size, label=None):
        start = self.pos
        if size < 0 or start + size > len(self.data):
            raise ValueError("Truncated transaction")
        self.pos += size
        if label:
            self.spans[label] = [start, self.pos]
        return self.data[start:self.pos]

    def uint(self, size, label=None):
        return int.from_bytes(self.take(size, label), "little")

    def length(self):
        value = 0
        for shift in range(0, 35, 7):
            byte = self.uint(1)
            value |= (byte & 127) << shift
            if not byte & 128:
                if value > 0xFFFFFFFF or (shift and byte == 0):
                    raise ValueError("Noncanonical ULEB128")
                return value
        raise ValueError("ULEB128 exceeds u32")

    def vector(self, read):
        return [read() for _ in range(self.length())]

    def blob(self, label=None):
        return self.take(self.length(), label)

    def address(self, label=None):
        return "0x" + self.take(32, label).hex()

    def argument(self):
        tag = self.length()
        if tag == 0:
            return "GasCoin"
        if tag in (1, 2):
            return {("Input" if tag == 1 else "Result"): self.uint(2)}
        if tag == 3:
            return {"NestedResult": [self.uint(2), self.uint(2)]}
        raise ValueError("Unsupported Argument")

    def command(self):
        tag = self.length()

        if tag == 0:
            package = self.address()
            module = self.blob().decode("utf-8")
            function = self.blob().decode("utf-8")

            if self.length() != 0:
                raise ValueError("This lab supports empty type arguments only")

            return {"MoveCall": dict(package=package, module=module,
                    function=function, type_arguments=[],
                    arguments=self.vector(self.argument))}
        if tag == 1:
            return {"TransferObjects": [self.vector(self.argument), self.argument()]}

        raise ValueError("This lab supports MoveCall and TransferObjects only")

    def object_ref(self):
        address = self.address()
        version = self.uint(8)
        digest = self.blob()
        if len(digest) != 32:
            raise ValueError("Expected a 32-byte digest")
        return [address, version, base58(digest)]

    def optional_u64(self):
        tag = self.uint(1)
        if tag == 0:
            return None
        if tag == 1:
            return self.uint(8)
        raise ValueError("Invalid Option tag")

def decode(raw):
    reader = Reader(raw)
    if reader.length() != 0 or reader.length() != 0:
        raise ValueError("Expected TransactionData::V1 and ProgrammableTransaction")

    inputs = []
    for index in range(reader.length()):
        if reader.length() != 0:
            raise ValueError("This lab supports pure inputs only")
        inputs.append({"Pure": list(reader.blob(f"input_{index}"))})

    commands = reader.vector(reader.command)
    sender = reader.address("sender")
    gas = dict(payment=reader.vector(reader.object_ref),
               owner=reader.address("gas_owner"),
               price=reader.uint(8, "gas_price"),
               budget=reader.uint(8, "gas_budget"))

    tag = reader.length()
    if tag == 0:
        expiration = "None"
    elif tag == 1:
        expiration = {"Epoch": reader.uint(8)}
    elif tag == 2:
        values = {name: reader.optional_u64() for name in
                  ("min_epoch", "max_epoch", "min_timestamp", "max_timestamp")}
        chain = reader.blob()
        if len(chain) != 32:
            raise ValueError("Expected a 32-byte chain identifier")
        values.update(chain=base58(chain), nonce=reader.uint(4))
        expiration = {"ValidDuring": values}
    else:
        raise ValueError("Unsupported expiration variant")
    if reader.pos != len(raw):
        raise ValueError("Trailing bytes")
    tx = {"V1": dict(kind={"ProgrammableTransaction": dict(inputs=inputs,
                      commands=commands)}, sender=sender, gas_data=gas,
                      expiration=expiration)}
    return tx, reader.spans

def read_bytes(path):
    return base64.b64decode(Path(path).read_text().strip(), validate=True)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("bytes_file")
    parser.add_argument("--official")

    args = parser.parse_args()
    raw = read_bytes(args.bytes_file)
    tx, spans = decode(raw)

    Path("evidence/decoded.json").write_text(json.dumps(tx, indent=2) + "\n")
    print("TransactionData bytes:", len(raw))

    for label in ("input_0", "input_1", "input_2", "gas_budget"):
        start, end = spans[label]
        print(f"{label} [{start}:{end}]: {raw[start:end].hex()}")

    print("Input(1) as u64:", int.from_bytes(bytes(tx["V1"]["kind"]
          ["ProgrammableTransaction"]["inputs"][1]["Pure"]), "little"))

    print("Sender:", tx["V1"]["sender"])
    print("Expiration:", json.dumps(tx["V1"]["expiration"], sort_keys=True))

    if args.official:
        official = json.loads(Path(args.official).read_text())["tx"]
        if tx != official:
            raise ValueError("Python and official decoding differ")
        print("Matches official decoder: True")

Run

sui keytool decode-or-verify-tx --tx-bytes "$TX_BYTES" --json > evidence/official-decoded.json
python3 client/decode_tx.py evidence/unsigned.b64 --official evidence/official-decoded.json

Output

TransactionData bytes: 398
input_0 [5:13]: 0700000000000000
input_1 [15:23]: 2a00000000000000
input_2 [25:57]: 173df66ee3d8b888de2e7a5a3fb2af02d3cacf8b84da33d612f22e9abcee9848
gas_budget [332:340]: 80f0fa0200000000
Input(1) as u64: 42
Sender: 0x95eb979fe75eca98735f4cd6dd6ea49c732e0a4aa13f5c73f9e20e15bd14a8a6
Expiration: {"ValidDuring": {"chain": "69WiPg3DAQiwdxfncX6wYQ2siKwAe6L9BZthQea3JNMD", "max_epoch": 1291, "max_timestamp": null, "min_epoch": 1290, "min_timestamp": null, "nonce": 2295501515}}
Matches official decoder: True
Terminal output of the Python decoder showing 398 transaction bytes, the byte offsets of the three inputs and the gas budget, the sender, the ValidDuring expiration and Matches official decoder: True

The notation [15:23] means byte offsets 15 through 22, counting from zero. That is the eight-byte payload of Input(1). Both the setter and the assertion refer to that one input, so this PTB contains only one encoded copy of the value they share.

The decoder walks every supported field and requires the entire buffer to be consumed. It also saves evidence/decoded.json. The final comparison checks that the reconstructed structure equals the native keytool’s structure, including the command arguments, gas data, and expiration.

In this run, gas_data.payment is empty because Alice pays from her address balance. The transaction contains a ValidDuring expiration with an epoch range, chain identifier, and nonce. The nonce distinguishes otherwise identical requests, while the bounded validity range limits how long the protocol must retain replay information. These fields are part of the signed transaction data. See the ValidDuring definition.

Add the signing intent

The transaction bytes describe an operation, but a signature also needs a context. Otherwise a verifier could interpret the same signed payload under an unrelated purpose. Sui adds an Intent with three fields, the message scope, intent version, and application ID. For a user transaction these bytes are 00 00 00, meaning TransactionData, V0, and Sui. See Sui’s intent signing reference.

intent message = 00 00 00 || BCS(TransactionData)
signing hash   = Blake2b-256(intent message)
signature      = Ed25519.sign(private_key, signing hash)

The || symbol means concatenate the byte sequences. Our transaction has 398 bytes, so the intent message has 401 bytes. Blake2b produces the 32-byte value passed to Ed25519. Ed25519 also performs its own internal hashing as part of that signature algorithm. We do not replace it with a second manual hash.

There are several zero bytes near the start of this example, but they belong to different layers. The three intent bytes precede the transaction’s BCS encoding. Within that encoding, the first two bytes identify TransactionData::V1 and ProgrammableTransaction. Keeping these layers separate will matter when we calculate the explorer’s transaction ID.

Diagram of one Sui TransactionData producing two hashes: with the 00 00 00 intent prefix, Blake2b-256 and Ed25519 it becomes the 97-byte signature, and with the TransactionData:: prefix, Blake2b-256 and Base58 it becomes the transaction digest shown in the explorer

Ask the CLI keystore to sign the saved request. The response includes the transaction bytes, intent message, signing hash, and serialized signature. Our reader prints the signature so we can see the public result without printing the longer byte fields again.

Run

sui keytool sign --address "$ALICE" --data "$TX_BYTES" --json > evidence/signature.json
SIG=$(python3 client/receipt.py evidence/signature.json --field signature)

python3 client/receipt.py evidence/signature.json --field signature

Output

APL6WbgQRutgwcY1OBB8rfyTjS8wG70zjEZ0VEvFoMiJ/IkjaDJrEHYifoYYdXGChKokqs1KgdIa6zAtedbPUwZ8tlXljWTiqL2Xd39LUJGv/Mbcl7uUNXRP1mIbvjzmeQ==

This is a signature over the constructed request. Signing can happen before submission, including in an offline signing environment. In this walkthrough the CLI performs the signer’s job, and Python will independently reconstruct what it signed. See Sui’s offline signing guide for the signing command.

Inspect and verify Alice’s signature

A verifier needs to know which signature algorithm to use and which public key to check. For an ordinary Sui Ed25519 signature, the serialized authenticator is 97 bytes. Its first byte selects Ed25519, the next 64 bytes contain the signature, and the final 32 bytes contain the public key. The Base64 string above is this complete authenticator in printable form. See Sui’s signature format.

Byte range     Contents
[0:1]          scheme flag 00
[1:65]         64-byte Ed25519 signature
[65:97]        32-byte Ed25519 public key

The public key also has to correspond to the expected signer. In our example Alice uses a normal Ed25519 address, derived as Blake2b-256(00 || public_key). The leading byte here identifies the key scheme. It belongs to address derivation and is separate from the three-byte signing intent. A signature can be mathematically valid for a key while that key belongs to a different address. See Sui address derivation.

The next program checks both the Ed25519 signature and the derived sender address. It reconstructs the intent message and signing hash, then compares those intermediate values with the native signer’s response. It also calculates the transaction digest that we’ll compare with the receipt after submission.

The transaction digest uses Blake2b-256("TransactionData::" || BCS(TransactionData)), displayed in Base58. That type-name prefix is UTF-8 text. The signing hash uses the three intent bytes instead. Changing the display encoding from Base64 to Base58 cannot turn one hash into the other because their preimages differ. The digest rule follows Sui’s typed hashing implementation and TransactionData digest method.

The CLI uses the field name digest for two different values. In evidence/signature.json, it contains the signing hash displayed in Base64. Alice signs the 32 hash bytes. In evidence/executed.json, it contains the transaction digest displayed in Base58, which we use to look up the transaction in the explorer.

Both are Blake2b-256 hashes of the same transaction bytes. Only the prefix, the encoding and the use differ:

ValueWhat is hashedDisplayWhere you see it
Signing hash00 00 00 plus the BCS TransactionDataBase64digest in evidence/signature.json
Transaction digestTransactionData:: plus the BCS TransactionDataBase58digest in evidence/executed.json and the explorer

Let’s create a file named client/verify_signature.py.

import argparse
import base64
import hashlib
import json
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

from decode_tx import base58, decode, read_bytes

def signing_hash(raw, intent=b"\x00\x00\x00"):
    return hashlib.blake2b(intent + raw, digest_size=32).digest()

def transaction_digest(raw):
    digest = hashlib.blake2b(b"TransactionData::" + raw, digest_size=32).digest()
    return base58(digest)

def verify(raw, serialized, intent=b"\x00\x00\x00"):
    envelope = base64.b64decode(serialized, validate=True)
    if len(envelope) != 97 or envelope[0] != 0:
        raise ValueError("This lab requires a 97-byte Ed25519 signature")

    signature, public_key = envelope[1:65], envelope[65:97]
    key = Ed25519PublicKey.from_public_bytes(public_key)
    address = "0x" + hashlib.blake2b(b"\x00" + public_key, digest_size=32).hexdigest()
    sender = decode(raw)[0]["V1"]["sender"]

    try:
        key.verify(signature, signing_hash(raw, intent))
        valid = True
    except InvalidSignature:
        valid = False
    return valid, address == sender, address, public_key

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("bytes_file")
    parser.add_argument("signer_json")
    parser.add_argument("--receipt")

    args = parser.parse_args()
    raw = read_bytes(args.bytes_file)
    signer = json.loads(Path(args.signer_json).read_text())
    valid, bound, address, public_key = verify(raw, signer["suiSignature"])

    print("Serialized signature bytes:", len(base64.b64decode(signer["suiSignature"])))
    print("Scheme flag: 00 (Ed25519)")
    print("Signature bytes: 64")
    print("Public key:", public_key.hex())
    print("Derived address:", address)
    print("Matches transaction sender:", bound)
    print("Signature verifies:", valid)

    digest = signing_hash(raw)
    print("Signing hash (hex):", digest.hex())
    print("Signing hash (Base64):", base64.b64encode(digest).decode())
    print("Matches keytool hash:", digest == base64.b64decode(signer["digest"]))
    print("Matches keytool intent bytes:", b"\x00\x00\x00" + raw ==
          base64.b64decode(signer["rawIntentMsg"]))
    print("Matches keytool transaction bytes:", raw == base64.b64decode(signer["rawTxData"]))
    print("Transaction digest:", transaction_digest(raw))

    if not (valid and bound):
        raise SystemExit("Signature or sender check failed")

    if args.receipt:
        receipt = json.loads(Path(args.receipt).read_text())
        matched = transaction_digest(raw) == receipt["digest"]
        print("Matches executed transaction digest:", matched)
        if not matched:
            raise SystemExit("Receipt identifies different transaction data")

Run

python3 client/verify_signature.py evidence/unsigned.b64 evidence/signature.json

Output

Serialized signature bytes: 97
Scheme flag: 00 (Ed25519)
Signature bytes: 64
Public key: 7cb655e58d64e2a8bd97777f4b5091affcc6dc97bb9435744fd6621bbe3ce679
Derived address: 0x95eb979fe75eca98735f4cd6dd6ea49c732e0a4aa13f5c73f9e20e15bd14a8a6
Matches transaction sender: True
Signature verifies: True
Signing hash (hex): eb34a0118ee7fee0823a60240c5b6befe786ca0a433815287da65666e52feefb
Signing hash (Base64): 6zSgEY7n/uCCOmAkDFtr7+eGygpDOBUofaZWZuUv7vs=
Matches keytool hash: True
Matches keytool intent bytes: True
Matches keytool transaction bytes: True
Transaction digest: DKEu7hbreKrVw89jAtvrnQbih8tzmasC6WEZrwbhDr5i
Terminal output of the signature verifier showing a 97-byte Ed25519 signature, the public key, the derived address matching the sender, Signature verifies: True, the signing hash and the transaction digest

Python verifies the signature against the reconstructed 32-byte signing hash. The public key hashes to Alice’s sender address, and all three comparisons with the keytool response are true. The Base58 transaction digest is already calculable before execution because its input is the request’s transaction data.

The cryptography library’s verify method raises InvalidSignature on verification failure. Our program converts that outcome into a Boolean for the experiments. This is a focused check for our generated Ed25519 signature. Sui’s native verifier remains the reference for its complete authentication rules and supported authenticator types. See the cryptography Ed25519 docs.

Check the same bytes and signature with Sui’s native keytool.

Run

sui keytool decode-or-verify-tx --tx-bytes "$TX_BYTES" --sig "$SIG" --json > evidence/native-verified.json
python3 client/receipt.py evidence/native-verified.json

Output

Native verification: {"Ok": null}

The response’s result field contains Ok. Inspect that field when automating this tool. In this CLI version, a failed signature verification can still return a successful process exit status while putting Err inside the JSON.

Change 42 to 43

What happens if a client edits the request after Alice signs it? We’ll keep her original signature and change the eight-byte payload of Input(1) from 42 to 43. Since the setter and assertion share this input, the altered program would consistently set and check 43 if it were freshly authorized.

We’ll copy the retained bytes and use the offsets found by our decoder. Rebuilding the PTB would make it harder to isolate this change because construction can choose different validity metadata. We’ll also make a second copy with the gas budget increased by one MIST. One MIST is the smallest SUI unit, and one SUI equals one billion MIST.

Let’s create a file named client/mutate_tx.py.

import base64
import json
from pathlib import Path

from decode_tx import decode, read_bytes
from verify_signature import transaction_digest, verify

raw = read_bytes("evidence/unsigned.b64")
signature = json.loads(Path("evidence/signature.json").read_text())["suiSignature"]
_, spans = decode(raw)

def changed(label, field, expected, replacement):
    start, end = spans[field]
    if int.from_bytes(raw[start:end], "little") != expected:
        raise ValueError("Unexpected baseline field")

    altered = bytearray(raw)
    altered[start:end] = replacement.to_bytes(end - start, "little")
    altered = bytes(altered)
    path = Path("evidence") / f"{label}.b64"
    path.write_text(base64.b64encode(altered).decode() + "\n")
    differences = [i for i, pair in enumerate(zip(raw, altered)) if pair[0] != pair[1]]

    print(f"{label}: changed byte offsets {differences}")
    print("  Original signature verifies:", verify(altered, signature)[0])
    print("  Transaction digest:", transaction_digest(altered))

print("Original signature verifies:", verify(raw, signature)[0])
changed("value-43", "input_1", 42, 43)
changed("budget-plus-one", "gas_budget", 50_000_000, 50_000_001)
print("Changed intent 030000 verifies:", verify(raw, signature, b"\x03\x00\x00")[0])

Run

python3 client/mutate_tx.py

Output

Terminal output of the mutation check: the original signature verifies, while changing the input from 42 to 43, raising the gas budget by one MIST or changing the intent to 03 00 00 makes it fail

The input mutation changes only byte 15, from 2a to 2b. The budget mutation changes only byte 332 in this encoding. Both changes produce a different transaction digest, and neither verifies against Alice’s original signature. The budget test shows that her authorization covers the transaction envelope as well as the Move arguments.

The last check keeps the transaction bytes fixed and substitutes intent bytes 03 00 00. Those bytes select the personal-message scope. We are testing the prefix change against the same payload here. A complete personal-message signing operation has its own payload encoding. The failed check shows that Alice’s signature also commits to the transaction signing context.

The mutation program saves both altered requests as Base64 files. Ask Sui to verify the changed-value request with the original signature too.

Run

CHANGED_BYTES=$(cat evidence/value-43.b64)
sui keytool decode-or-verify-tx --tx-bytes "$CHANGED_BYTES" --sig "$SIG" --json > evidence/changed-native.json
python3 client/receipt.py evidence/changed-native.json

Output

Native verification: {"Err": {"InvalidSignature": {"error": "Fail to verify user sig Invalid signature was given to the function"}}}

The native verifier reports InvalidSignature. These mutation checks are local and submit no transactions. To authorize an edited request, the client must present its changed contents to the signer and obtain a signature for those bytes.

Submit the bytes we verified

We now have a decoded request, a valid signature, and a calculated transaction digest. Submit the original TX_BYTES and SIG. The command below executes on Testnet and pays gas from Alice’s Testnet funds.

Run

sui client execute-signed-tx --tx-bytes "$TX_BYTES" --signatures "$SIG" --json > evidence/executed.json
python3 client/receipt.py evidence/executed.json

Output

Digest: DKEu7hbreKrVw89jAtvrnQbih8tzmasC6WEZrwbhDr5i
Status: success
EditCap: 0x953d2720c5d8f060a2b9ce2fc8bd6eb119710693f9277aed46f4860dfde78f38
Owner: 0x173df66ee3d8b888de2e7a5a3fb2af02d3cacf8b84da33d612f22e9abcee9848
Notebook: 0xaadcc69570e424e6125860161c1e600b530fcd8de68414e070e802d9da932a4c
Owner: 0x173df66ee3d8b888de2e7a5a3fb2af02d3cacf8b84da33d612f22e9abcee9848

The receipt reports success and lists the notebook and editing capability owned by Bob. Open the transaction in SuiVision and check its status and sender.

SuiVision page of the executed transaction with status Success, sender 0x95eb…a8a6 and a total gas fee of 3,926,000 MIST

Now compare the receipt’s digest with the value calculated from the retained bytes. The verifier’s optional --receipt argument performs that comparison.

Run

python3 client/verify_signature.py evidence/unsigned.b64 evidence/signature.json --receipt evidence/executed.json

Output, final two lines

Transaction digest: DKEu7hbreKrVw89jAtvrnQbih8tzmasC6WEZrwbhDr5i
Matches executed transaction digest: True

The matching value identifies exactly the transaction data we inspected. The signature itself is carried alongside that data and is absent from the transaction-digest preimage. The notebook’s object ID is another identifier, produced when the transaction executes its constructor. It answers which object was created, while the transaction digest answers which request was submitted.

Read the new notebook using the ID from the effects.

Run

NOTEBOOK=$(python3 client/receipt.py evidence/executed.json --field notebook)
sui client object "$NOTEBOOK" --json > evidence/notebook.json
python3 client/receipt.py evidence/notebook.json

Output

Notebook: 0xaadcc69570e424e6125860161c1e600b530fcd8de68414e070e802d9da932a4c
Value: 42
Version: 1
Owner: 0x173df66ee3d8b888de2e7a5a3fb2af02d3cacf8b84da33d612f22e9abcee9848

The notebook holds 42 and belongs to Bob. This is the result of the original request. The locally mutated request with value 43 was never submitted.

On Chainstack nodes. Signing happens locally, so a node is only needed to submit and read. A Chainstack Sui node serves TransactionExecutionService over gRPC for executing and simulating transactions, with your token in the x-token header. See Sui tooling.

In SuiVision, open the same transaction’s User Signatures tab. It shows Ed25519, Alice’s account, and the signature bytes. This view separates the signature from the scheme and account, so its displayed signature string is shorter than our complete 97-byte serialized authenticator.

SuiVision User Signatures tab showing the ED25519 schema, Alice’s account address and the signature

Local signature verification establishes that the key authorized these bytes. Network acceptance also depends on the transaction’s current validity, gas funding, input availability, and protocol checks. The Move program then has its own execution rules, including the capability and value assertions we exercised in Part 4. A valid signature alone cannot guarantee that an application call succeeds. See Sui’s transaction lifecycle.

Our example uses one ordinary Ed25519 sender and the same address as gas payer. Sponsored transactions, multisig, zkLogin, passkeys, and address aliases have additional authentication rules. The byte tracing here gives us the foundation for examining those paths without treating every authenticator as a 97-byte value.

Summary

A Sui user transaction carries a PTB together with its sender, gas data, and expiration. BCS turns that structured request into canonical bytes. For transaction signing, Sui prepends the three-byte intent and hashes the result with Blake2b-256. An Ed25519 signer authorizes that 32-byte hash, and its serialized authenticator carries the scheme flag, signature, and public key.

Changing a shared PTB input or the gas budget changes the authorized request. The original signature then fails verification. The explorer’s transaction digest is calculated separately with the TransactionData:: prefix, which is why we can compute it before submission and compare it with the executed receipt.

We can now follow a value from a PTB command into the bytes Alice authorizes and the state Sui eventually commits. The next useful question is how authorization changes when the sender and gas payer are different accounts.

FAQ

What does a Sui wallet sign?

A Sui wallet signs a hash of the transaction’s BCS-serialized TransactionData, prefixed with a three-byte intent. TransactionData contains the PTB, the sender, the gas data and the expiration, so changing any of them invalidates the signature.

What is the intent in Sui signing?

The intent is a three-byte prefix with a message scope, an intent version and an application ID. For a user transaction it is 00 00 00, which means TransactionData, V0 and Sui. Prefixing the same payload with 03 00 00, the personal-message scope, makes the original signature fail.

How long is a Sui Ed25519 signature?

A serialized Ed25519 signature on Sui is 97 bytes: one scheme flag byte (00 for Ed25519), the 64-byte signature and the 32-byte public key. The sender address is the Blake2b-256 hash of the flag byte plus the public key.

Is the Sui signing hash the same as the transaction digest?

No. Both are Blake2b-256 hashes of the same BCS bytes, but the signing hash uses the 00 00 00 intent prefix and the transaction digest uses the TransactionData:: prefix. The digest is shown in Base58, is what the explorer uses, and can be calculated before submission.

What happens if one byte of a signed Sui transaction changes?

The signature no longer verifies and the transaction digest changes. In our Testnet run, changing the shared input from 42 to 43 and raising the gas budget by one MIST both made the original signature fail.

Can I sign a Sui transaction offline?

Yes. Build and serialize the unsigned transaction, sign the bytes elsewhere, then submit the same bytes with the signature. Keep the exact bytes, because building the transaction again can choose new metadata such as a different validity nonce.

SHARE THIS ARTICLE
Customer Stories

Crouton Finance

Crouton Finance powers TON’s DeFi with a high-performance DEX, synthetic assets protocol, and reliable Chainstack RPCs.

Kiln

Kiln uses Chainstack Subgraphs to manage $13B+ in staked assets.

Spanning Labs

Spanning Labs optimizes its multi-region implementation and minimizes cloud infrastructure costs for its cross-chain relayer.