Skip to content

Instantly share code, notes, and snippets.

@flokli
Created November 27, 2022 23:25
Show Gist options
  • Save flokli/9534f8b2db23f13feecd228435830e68 to your computer and use it in GitHub Desktop.
Save flokli/9534f8b2db23f13feecd228435830e68 to your computer and use it in GitHub Desktop.
Some bit twiddling to realize FOD output path calculation uses the NAR representation of the contents, at least when not interacting with directories.
package main
import (
"encoding/hex"
"fmt"
nixhash "github.com/nix-community/go-nix/pkg/hash"
"github.com/nix-community/go-nix/pkg/nixbase32"
)
func main() {
// $ nix-build -A third_party.nixpkgs.helix.src
// /nix/store/ppv6f5hbjiyylzmzlhyap0np0hnvgvrm-source
// $ curl http://cache.nixos.org/ppv6f5hbjiyylzmzlhyap0np0hnvgvrm.narinfo
// StorePath: /nix/store/ppv6f5hbjiyylzmzlhyap0np0hnvgvrm-source
// URL: nar/0bx02akdwj2dx6bivpaacwbyfavdqfgl7hdz1a2cck60jbqz7rbv.nar.xz
// Compression: xz
// FileHash: sha256:0bx02akdwj2dx6bivpaacwbyfavdqfgl7hdz1a2cck60jbqz7rbv
// FileSize: 75367028
// NarHash: sha256:09lg4f80s1vybsw2nl8jgl1jqzvvqvfk8pdmg7gdw54y299j3856
// NarSize: 653811776
// References:
// Deriver: 9pja3bj31rwwdphxqqmvqgfxw78zzm12-source.drv
// Sig: cache.nixos.org-1:iLR0UvlHKLRSYRQLE6YjnIKJ1Tk7TgF906FLM0JrR0LVgvyDjVhXkgkYtV7fbRU7C/6M6r7CUaiLgf8tf6aoBw==
// CA: fixed:r:sha256:09lg4f80s1vybsw2nl8jgl1jqzvvqvfk8pdmg7gdw54y299j3856
// $ nix-instantiate -A third_party.nixpkgs.helix.src
// /nix/store/scyjy4l5xy52scmr59m8lnfl5k12yjhj-source.drv
// $ nix show-derivation /nix/store/scyjy4l5xy52scmr59m8lnfl5k12yjhj-source.drv
// says:
//
// "outputs": {
// "out": {
// "path": "/nix/store/ppv6f5hbjiyylzmzlhyap0np0hnvgvrm-source",
// "hashAlgo": "r:sha256",
// "hash": "a6a02153129e14dede79b55d34ddc67b7f2c037d12512bb85e7e070d90238f26"
// }
// },
// Let's figure out how this "a6a02153129e14dede79b55d34ddc67b7f2c037d12512bb85e7e070d90238f26" was produced
s := "a6a02153129e14dede79b55d34ddc67b7f2c037d12512bb85e7e070d90238f26"
fmt.Printf("hash as encoding/hex: %v\n", s)
dgst, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
fmt.Printf("encoded: %x\n", dgst)
compressed := nixhash.CompressHash(dgst, 32)
fmt.Printf("compressed: %x\n", compressed)
fmt.Printf("compressed nixbase32: %v\n", nixbase32.EncodeToString(compressed))
// does output 09lg4f80s1vybsw2nl8jgl1jqzvvqvfk8pdmg7gdw54y299j3856
// … which is what NarHash in the output above says
// So yeah, fixed output derivations hash the NAR representation of a File/
// Directory/…, and this means we need to produce a NAR in memory to end up with
// the same hashing.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment