ContentsSHA-256

SHA-256

On this page
  1. Input and result
  2. Costs
  3. Calling or linking

A reference program, not part of the protocol: the chain runs it like any other deployment. See Reference programs.

sha256 returns the SHA-256 digest of its input, for programs that call a hash function rather than carry one in their own code. It is plain SHA-256, not the domain-separated H of the protocol and of the conventions. A program that wants H(tag, x) from it passes the whole string "Ting/" ‖ u16(len(tag)) ‖ tag ‖ x as input.

Input and result#

PartContent
InputThe message: the whole input, of any length
ResultIts SHA-256 digest, 32 bytes

Every input is a valid message, so the program never reverts. Empty input is the empty message, whose digest is

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

and so the deployment invocation with empty input (the deployment invocation), which is the program's canonical deployment, succeeds. The program keeps no state and emits no events, so a read-only call behaves exactly like an ordinary one.

Costs#

A call costs about 264,000 C for a short message and about 16,100 C for each further 64-byte block. Most of the first figure is fixed: the program's code price, which a transaction pays only the first time it runs sha256, and a fresh instance, about 84,000 C (the cost of an invocation). SHA-256 pads a message of n bytes to ceil((n + 9) / 64) blocks, so a short message, one block, is at most 55 bytes. Hashing 1,000 bytes, 16 blocks, costs about 264,000 + 15 × 16,100, roughly 507,000 C. Like every invocation, a call also reads 2 S, and returning the digest costs 32 D (output).

Calling or linking#

A program that links its own SHA-256 code pays about the same 16,100 C per block, but nothing for the call itself: no 2 S for reading sha256, no code price for its 2,474 bytes, no fresh instance, no copying of the message into a second program and the digest back, and no D for the result. Linking is therefore cheaper for most uses.

What calling saves is code size. A program that links SHA-256 pays for that code as part of its own code price, whether it hashes or not; one that calls sha256 pays for the call only when it hashes. For long messages the blocks dominate either way.