Back to Fuels Ts

Sway Script With Signature Validation

apps/docs/src/guide/cookbook/sway-script-with-signature-validation.md

0.103.02.1 KB
Original Source

Sway Script With Signature Validation

This guide explains how to work with a Script that rely on in-code signature validation. This is particularly useful when you need to verify that a transaction was authorized by a specific account.

Example Sway Script

Here's an example of a Sway script that validates signatures:

<<< @/../../docs/sway/script-signing/src/main.sw#multiple-signers-1{rust:line-numbers}

This script:

  1. Takes 2 parameters; an account address and an witness index
  2. Recovers the entry witness from the transaction's witnesses array using the given index
  3. Validates if the signature was generated by the given account address
  4. Returns true or false based on the validation result

Understanding Signature Validation in Fuel

On Fuel, transaction signing involves using a wallet's private key to create a hash based on the transaction ID (which is the same as the transaction hash). The transaction ID is generated by hashing the transaction bytes themselves.

Important considerations:

  • Any modification to the transaction after signing will invalidate the signature (modification within the witnesses array do not invalidate the signature)
  • This is because the transaction ID changes when the transaction is modified
  • The signature is typically the last thing added to a transaction, after estimation and funding

Special Considerations for Estimation

When working with Sway programs that have in-code signature validation, the estimation process becomes more complex because:

  1. A valid signature is required during the estimation process
  2. The signature must be valid for both during the transaction estimation and later when submitting the transaction
  3. The transaction may be modified during the estimation and funding process, which will result in invalidating any previously added signature

Implementation Example

Here's how to properly implement a transaction with signature validation for this specific Sway script:

<<< @./snippets/signature-script.ts#signature-script{ts:line-numbers}