How do I precalculate the `narHash` for a Flake input?

Given a newly created flake (using nix flake init), and the following flake.lock file:

{
  "nodes": {
    "nixpkgs": {
      "locked": {
        "lastModified": 1764950072,
        "narHash": "sha256-BmPWzogsG2GsXZtlT+MTcAWeDK5hkbGRZTeZNW42fwA=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "f61125a668a320878494449750330ca58b78c557",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "root": {
      "inputs": {
        "nixpkgs": "nixpkgs"
      }
    }
  },
  "root": "root",
  "version": 7
}

How do I precalculate the narHash for the nixpkgs input?

I tried the following but those produced different outputs:

$ nix-prefetch-url https://github.com/nixos/nixpkgs/archive/f61125a668a320878494449750330ca58b78c557.tar.gz
#=> path is '/nix/store/fxcafl2s6n7ixxpv8i6dkbzs786gfx0d-f61125a668a320878494449750330ca58b78c557.tar.gz'
#=> 035r92kgv4sbslwi3ss63n53hplm8s5csqd2mzxrlkxpxx8v8476

$ nix-prefetch-url https://github.com/nixos/nixpkgs/archive/f61125a668a320878494449750330ca58b78c557.tar.gz --unpack
#=> path is '/nix/store/g8v1l82j4wnz6avqcvby7x82jwbcrrc3-f61125a668a320878494449750330ca58b78c557.tar.gz'
#=> 003z6rp3b69pcn8v34b1mq69w1bh2gilyrcvbnn626rci37dcqq6

Out of curiosity, what’s your use case for wanting to pre-calculate the hash?

Well, yes, one is a hash of the unpacked tarfile and one is hashing the gzipped file itself.

Also keep in mind those are not the same format - you’re looking for the SRI hash, so pass that to nix hash to-sri --type sha256 <hash>. The unpacked archive will match the narHash in the flake.lock:

$ nix hash to-sri --type sha256 003z6rp3b69pcn8v34b1mq69w1bh2gilyrcvbnn626rci37dcqq6 
sha256-BmPWzogsG2GsXZtlT+MTcAWeDK5hkbGRZTeZNW42fwA=

TL;DR: I want to overengineer something.


I want to be able to lock nixpkgs to a specific commit. I know I can just specify the rev in flake.nix, or just put the new commit in flake.lock and get the correct hash from nixos-rebuild’s error message, but where’s the fun in that :wink:

And here I was, thinking that the SRI format is just the original hash with sha256- prefixed :slight_smile:

Depends what base it’s in - SRI is base 64, the sha256 hash could be base 36 or 64.

1 Like

I guess:

nix flake update nixpkgs --override-input nixpkgs github:NixOS/nixpkgs/878e468e02bfabeda08c79250f7ad583037f2227

is also unfun for you?

Yes, but in a good way, it does exactly what I want to achieve. Thanks!