theultraman20

validate zig

Aug 20th, 2025 (edited)
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.66 KB | None | 0 0
  1.     pub fn validate(scriptSig: []const u8, scriptPubKey: []const u8, transaction: ?*Tx, input_index: ?usize, alloc: mem.Allocator) Error!bool {
  2.         const Op = Script.Opcode;
  3.  
  4.         var stack = try Stack.init(scriptSig.len + scriptPubKey.len, alloc);
  5.         defer stack.deinit(alloc);
  6.         stack.setAlloc(alloc);
  7.  
  8.         const Local = struct {
  9.             fn handleError(err: Script.RunError) !bool {
  10.                 return switch (err) {
  11.                     error.Internal, error.StackFull => error.Internal,
  12.                     mem.Allocator.Error.OutOfMemory => error.OutOfMemory,
  13.                     error.BadScript, error.VerifyFailed => false,
  14.                 };
  15.             }
  16.         };
  17.  
  18.  
  19.         // detect and handle special p2sh pattern
  20.         const is_p2sh = scriptPubKey[0] == Op.HASH_160 and
  21.             scriptPubKey[1] == Op.OP_PUSHDATA1 and
  22.             scriptPubKey[2] == 0x14 and
  23.             scriptPubKey[22] == Op.OP_EQUAL;
  24.  
  25.         var redeem_buf: [Stack.MAX_STACK_ELEMENT_SIZE]u8 = undefined;
  26.         var redeem_script: []u8 = undefined;
  27.  
  28.         Script.run(scriptSig, &stack, transaction, input_index, alloc) catch |err| return Local.handleError(err);
  29.         if (is_p2sh) {
  30.             redeem_script = stack.pop(&redeem_buf) catch |err| return Local.handlePopError(err);
  31.             stack.push(redeem_script);
  32.         }
  33.         Script.run(scriptPubKey, &stack, transaction, input_index, alloc) catch |err| return Local.handleError(err);
  34.  
  35.         if (is_p2sh) {
  36.             Script.run(&redeem_script, &stack, transaction, input_index, alloc) catch |err| return Local.handleError(err);
  37.         }
  38.  
  39.         return stack.verify();
  40.     }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment