Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ValidPathInfo: make ca field a proper datatype #3649

Merged
Merged
Show file tree
Hide file tree
Changes from 44 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
bcde545
Flip dependency so store-api.hh includes derivations.hh
Ericson2314 Mar 21, 2020
f4b89e1
Merge branch 'no-stringly-typed-derivation-output' of github.com:Eric…
meditans Jun 1, 2020
0cb67ec
Merge branch 'derivation-header-include-order' of github.com:Ericson2…
meditans Jun 1, 2020
0e9438b
Create new file-hash files
meditans Jun 1, 2020
da39092
WIP
meditans Jun 1, 2020
754c910
WIP more progress
Ericson2314 Jun 1, 2020
efcd30d
WIP
Ericson2314 Jun 2, 2020
1b6461f
Merge remote-tracking branch 'upstream/master' into validPathInfo-ca-…
Ericson2314 Jun 2, 2020
a5d820a
Change parseCa(Opt) to parseContentAddress(Opt)
meditans Jun 2, 2020
25e6181
Apply suggestions from code review
Ericson2314 Jun 2, 2020
a33270c
Clean up `ValidPathInfo::isContentAddressed` with `std::visit`
Ericson2314 Jun 2, 2020
390bf64
WIP
meditans Jun 2, 2020
343c20a
WIP Completed implementation
meditans Jun 2, 2020
fd2eb41
Move file-hash to content-address
meditans Jun 2, 2020
a5cdf18
Add assertions for SHA256 in fixed case
meditans Jun 2, 2020
78f137e
Validate text version instead, throw Errors
meditans Jun 2, 2020
75d2581
Typo
meditans Jun 2, 2020
39ba87b
Missing `#include <cassert>` in `lru-cache.hh`
Ericson2314 Jun 2, 2020
fecff16
Merge remote-tracking branch 'obsidian/missing-include-0' into validP…
Ericson2314 Jun 2, 2020
3c78ac3
Merge remote-tracking branch 'obsidian/no-hash-type-unknown' into val…
Ericson2314 Jun 2, 2020
53bc8ff
No C++ designated initializers yet with Clang 7
Ericson2314 Jun 4, 2020
574d546
Make sure info.ca tag bit is set in `nix add-to-store`
Ericson2314 Jun 4, 2020
ed86acf
Use some `std::optional::has_value` for clarity
Ericson2314 Jun 4, 2020
2041499
Flip boolean
Ericson2314 Jun 4, 2020
744ce9c
Merge branch 'master' of github.com:NixOS/nix into validPathInfo-ca-p…
Ericson2314 Jun 4, 2020
94ddea9
Use `readString` rather than `>> temporary`
Ericson2314 Jun 4, 2020
d614166
Fix condition error and make test suite pass
meditans Jun 4, 2020
669c399
Merge branch 'no-hash-type-unknown' into validPathInfo-temp
Ericson2314 Jun 18, 2020
3f8dcfe
Merge branch 'validPathInfo-temp' into validPathInfo-ca-proper-datatype
Ericson2314 Jun 18, 2020
3fc58a9
Remove some `Base::` that crept in
Ericson2314 Jun 19, 2020
2f0e395
Merge remote-tracking branch 'me/no-stringly-typed-derivation-output'…
Ericson2314 Jun 19, 2020
911fc88
More designated initializers
Ericson2314 Jun 19, 2020
29691ed
Merge remote-tracking branch 'upstream/master' into validPathInfo-ca-…
Ericson2314 Jun 19, 2020
e288c09
Merge remote-tracking branch 'upstream/master' into validPathInfo-ca-…
Ericson2314 Jun 19, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/libexpr/get-drvs.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#include "get-drvs.hh"
#include "util.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "store-api.hh"

#include <cstring>
#include <regex>
Expand Down
21 changes: 10 additions & 11 deletions src/libexpr/primops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -769,15 +769,14 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
.nixCode = NixCode { .errPos = posDrvName }
});

HashType ht = outputHashAlgo.empty() ? htUnknown : parseHashType(outputHashAlgo);

std::optional<HashType> ht = parseHashTypeOpt(outputHashAlgo);
Hash h = newHashAllowEmpty(*outputHash, ht);

auto outPath = state.store->makeFixedOutputPath(ingestionMethod, h, drvName);
if (!jsonObject) drv.env["out"] = state.store->printStorePath(outPath);
drv.outputs.insert_or_assign("out", DerivationOutput {
.path = std::move(outPath),
.hash = DerivationOutputHash {
.hash = FixedOutputHash {
.method = ingestionMethod,
.hash = std::move(h),
},
Expand All @@ -796,7 +795,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
drv.outputs.insert_or_assign(i,
DerivationOutput {
.path = StorePath::dummy,
.hash = std::optional<DerivationOutputHash> {},
.hash = std::optional<FixedOutputHash> {},
});
}

Expand All @@ -808,7 +807,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
drv.outputs.insert_or_assign(i,
DerivationOutput {
.path = std::move(outPath),
.hash = std::optional<DerivationOutputHash>(),
.hash = std::optional<FixedOutputHash>(),
});
}
}
Expand Down Expand Up @@ -1006,8 +1005,8 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Value & v)
{
string type = state.forceStringNoCtx(*args[0], pos);
HashType ht = parseHashType(type);
if (ht == htUnknown)
std::optional<HashType> ht = parseHashType(type);
if (!ht)
throw Error({
.hint = hintfmt("unknown hash type '%1%'", type),
.nixCode = NixCode { .errPos = pos }
Expand All @@ -1016,7 +1015,7 @@ static void prim_hashFile(EvalState & state, const Pos & pos, Value * * args, Va
PathSet context; // discarded
Path p = state.coerceToPath(pos, *args[1], context);

mkString(v, hashFile(ht, state.checkSourcePath(p)).to_string(Base16, false), context);
mkString(v, hashFile(*ht, state.checkSourcePath(p)).to_string(Base16, false), context);
}

/* Read a directory (without . or ..) */
Expand Down Expand Up @@ -1943,8 +1942,8 @@ static void prim_stringLength(EvalState & state, const Pos & pos, Value * * args
static void prim_hashString(EvalState & state, const Pos & pos, Value * * args, Value & v)
{
string type = state.forceStringNoCtx(*args[0], pos);
HashType ht = parseHashType(type);
if (ht == htUnknown)
std::optional<HashType> ht = parseHashType(type);
if (!ht)
throw Error({
.hint = hintfmt("unknown hash type '%1%'", type),
.nixCode = NixCode { .errPos = pos }
Expand All @@ -1953,7 +1952,7 @@ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args,
PathSet context; // discarded
string s = state.forceString(*args[1], context, pos);

mkString(v, hashString(ht, s).to_string(Base16, false), context);
mkString(v, hashString(*ht, s).to_string(Base16, false), context);
}


Expand Down
2 changes: 1 addition & 1 deletion src/libexpr/primops/context.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#include "primops.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "store-api.hh"

namespace nix {

Expand Down
2 changes: 1 addition & 1 deletion src/libfetchers/fetchers.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ std::unique_ptr<Input> inputFromAttrs(const Attrs & attrs)
if (res) {
if (auto narHash = maybeGetStrAttr(attrs, "narHash"))
// FIXME: require SRI hash.
res->narHash = newHashAllowEmpty(*narHash, htUnknown);
res->narHash = newHashAllowEmpty(*narHash, {});
return res;
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/libfetchers/tarball.cc
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ DownloadFileResult downloadFile(
ValidPathInfo info(store->makeFixedOutputPath(FileIngestionMethod::Flat, hash, name));
info.narHash = hashString(htSHA256, *sink.s);
info.narSize = sink.s->size();
info.ca = makeFixedOutputCA(FileIngestionMethod::Flat, hash);
info.ca = FixedOutputHash {
FileIngestionMethod::Flat,
hash,
};
auto source = StringSource { *sink.s };
store->addToStore(info, source, NoRepair, NoCheckSigs);
storePath = std::move(info.path);
Expand Down Expand Up @@ -264,7 +267,7 @@ struct TarballInputScheme : InputScheme

auto input = std::make_unique<TarballInput>(parseURL(getStrAttr(attrs, "url")));
if (auto hash = maybeGetStrAttr(attrs, "hash"))
input->hash = newHashAllowEmpty(*hash, htUnknown);
input->hash = newHashAllowEmpty(*hash, {});

return input;
}
Expand Down
15 changes: 9 additions & 6 deletions src/libstore/build.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3714,7 +3714,7 @@ void DerivationGoal::registerOutputs()
/* Check that fixed-output derivations produced the right
outputs (i.e., the content hash should match the specified
hash). */
std::string ca;
std::optional<ContentAddress> ca;

if (fixedOutput) {

Expand All @@ -3730,8 +3730,8 @@ void DerivationGoal::registerOutputs()
/* Check the hash. In hash mode, move the path produced by
the derivation to its content-addressed location. */
Hash h2 = i.second.hash->method == FileIngestionMethod::Recursive
? hashPath(i.second.hash->hash.type, actualPath).first
: hashFile(i.second.hash->hash.type, actualPath);
? hashPath(*i.second.hash->hash.type, actualPath).first
: hashFile(*i.second.hash->hash.type, actualPath);

auto dest = worker.store.makeFixedOutputPath(i.second.hash->method, h2, i.second.path.name());

Expand Down Expand Up @@ -3764,7 +3764,7 @@ void DerivationGoal::registerOutputs()
else
assert(worker.store.parseStorePath(path) == dest);

ca = makeFixedOutputCA(i.second.hash->method, h2);
ca = FixedOutputHash { i.second.hash->method, h2 };
}

/* Get rid of all weird permissions. This also checks that
Expand Down Expand Up @@ -3837,7 +3837,10 @@ void DerivationGoal::registerOutputs()
info.ca = ca;
worker.store.signPathInfo(info);

if (!info.references.empty()) info.ca.clear();
if (!info.references.empty()) {
// FIXME don't we have an experimental feature for fixed output with references?
info.ca = {};
}

infos.emplace(i.first, std::move(info));
}
Expand Down Expand Up @@ -4997,7 +5000,7 @@ bool Worker::pathContentsGood(const StorePath & path)
if (!pathExists(store.printStorePath(path)))
res = false;
else {
HashResult current = hashPath(info->narHash.type, store.printStorePath(path));
HashResult current = hashPath(*info->narHash.type, store.printStorePath(path));
Hash nullHash(htSHA256);
res = info->narHash == nullHash || info->narHash == current.first;
}
Expand Down
4 changes: 2 additions & 2 deletions src/libstore/builtins/fetchurl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ void builtinFetchurl(const BasicDerivation & drv, const std::string & netrcData)
for (auto hashedMirror : settings.hashedMirrors.get())
try {
if (!hasSuffix(hashedMirror, "/")) hashedMirror += '/';
auto ht = parseHashType(getAttr("outputHashAlgo"));
auto ht = parseHashTypeOpt(getAttr("outputHashAlgo"));
auto h = Hash(getAttr("outputHash"), ht);
fetch(hashedMirror + printHashType(h.type) + "/" + h.to_string(Base16, false));
fetch(hashedMirror + printHashType(*h.type) + "/" + h.to_string(Base16, false));
return;
} catch (Error & e) {
debug(e.what());
Expand Down
79 changes: 79 additions & 0 deletions src/libstore/content-address.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#include "content-address.hh"

namespace nix {

std::string FixedOutputHash::printMethodAlgo() const {
return makeFileIngestionPrefix(method) + printHashType(*hash.type);
}

std::string makeFileIngestionPrefix(const FileIngestionMethod m) {
switch (m) {
case FileIngestionMethod::Flat:
return "";
case FileIngestionMethod::Recursive:
return "r:";
default:
throw Error("impossible, caught both cases");
}
}

std::string makeFixedOutputCA(FileIngestionMethod method, const Hash & hash)
{
return "fixed:"
+ makeFileIngestionPrefix(method)
+ hash.to_string(Base32, true);
}

// FIXME Put this somewhere?
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

std::string renderContentAddress(ContentAddress ca) {
return std::visit(overloaded {
[](TextHash th) {
return "text:" + th.hash.to_string(Base32, true);
},
[](FixedOutputHash fsh) {
return makeFixedOutputCA(fsh.method, fsh.hash);
}
}, ca);
}

ContentAddress parseContentAddress(std::string_view rawCa) {
auto prefixSeparator = rawCa.find(':');
if (prefixSeparator != string::npos) {
auto prefix = string(rawCa, 0, prefixSeparator);
if (prefix == "text") {
auto hashTypeAndHash = rawCa.substr(prefixSeparator+1, string::npos);
Hash hash = Hash(string(hashTypeAndHash));
if (*hash.type != htSHA256) {
throw Error("parseContentAddress: the text hash should have type SHA256");
}
return TextHash { hash };
} else if (prefix == "fixed") {
// This has to be an inverse of makeFixedOutputCA
auto methodAndHash = rawCa.substr(prefixSeparator+1, string::npos);
if (methodAndHash.substr(0,2) == "r:") {
std::string_view hashRaw = methodAndHash.substr(2,string::npos);
return FixedOutputHash { FileIngestionMethod::Recursive, Hash(string(hashRaw)) };
} else {
std::string_view hashRaw = methodAndHash;
return FixedOutputHash { FileIngestionMethod::Flat, Hash(string(hashRaw)) };
}
} else {
throw Error("parseContentAddress: format not recognized; has to be text or fixed");
}
} else {
throw Error("Not a content address because it lacks an appropriate prefix");
}
};

std::optional<ContentAddress> parseContentAddressOpt(std::string_view rawCaOpt) {
return rawCaOpt == "" ? std::optional<ContentAddress> {} : parseContentAddress(rawCaOpt);
};

std::string renderContentAddress(std::optional<ContentAddress> ca) {
return ca ? renderContentAddress(*ca) : "";
}

}
56 changes: 56 additions & 0 deletions src/libstore/content-address.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#pragma once

#include <variant>
#include "hash.hh"

namespace nix {

enum struct FileIngestionMethod : uint8_t {
Flat = false,
Recursive = true
};

struct TextHash {
Hash hash;
};

/// Pair of a hash, and how the file system was ingested
struct FixedOutputHash {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with FixedOutputHash for this PR, now that it is not just used in derivations.

FileIngestionMethod method;
Hash hash;
std::string printMethodAlgo() const;
};

/*
We've accumulated several types of content-addressed paths over the years;
fixed-output derivations support multiple hash algorithms and serialisation
methods (flat file vs NAR). Thus, ‘ca’ has one of the following forms:

* ‘text:sha256:<sha256 hash of file contents>’: For paths
computed by makeTextPath() / addTextToStore().

* ‘fixed:<r?>:<ht>:<h>’: For paths computed by
makeFixedOutputPath() / addToStore().
*/
typedef std::variant<
TextHash, // for paths computed by makeTextPath() / addTextToStore
FixedOutputHash // for path computed by makeFixedOutputPath
> ContentAddress;

/* Compute the prefix to the hash algorithm which indicates how the files were
ingested. */
std::string makeFileIngestionPrefix(const FileIngestionMethod m);

/* Compute the content-addressability assertion (ValidPathInfo::ca)
for paths created by makeFixedOutputPath() / addToStore(). */
std::string makeFixedOutputCA(FileIngestionMethod method, const Hash & hash);

std::string renderContentAddress(ContentAddress ca);

std::string renderContentAddress(std::optional<ContentAddress> ca);

ContentAddress parseContentAddress(std::string_view rawCa);

std::optional<ContentAddress> parseContentAddressOpt(std::string_view rawCaOpt);

}
5 changes: 3 additions & 2 deletions src/libstore/daemon.cc
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
if (GET_PROTOCOL_MINOR(clientVersion) >= 16) {
to << info->ultimate
<< info->sigs
<< info->ca;
<< renderContentAddress(info->ca);
}
} else {
assert(GET_PROTOCOL_MINOR(clientVersion) >= 17);
Expand Down Expand Up @@ -710,7 +710,8 @@ static void performOp(TunnelLogger * logger, ref<Store> store,
info.references = readStorePaths<StorePathSet>(*store, from);
from >> info.registrationTime >> info.narSize >> info.ultimate;
info.sigs = readStrings<StringSet>(from);
from >> info.ca >> repair >> dontCheckSigs;
info.ca = parseContentAddressOpt(readString(from));
from >> repair >> dontCheckSigs;
if (!trusted && dontCheckSigs)
dontCheckSigs = false;
if (!trusted)
Expand Down
17 changes: 4 additions & 13 deletions src/libstore/derivations.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@

namespace nix {

std::string DerivationOutputHash::printMethodAlgo() const {
return makeFileIngestionPrefix(method) + printHashType(hash.type);
}


const StorePath & BasicDerivation::findOutput(const string & id) const
{
auto i = outputs.find(id);
Expand Down Expand Up @@ -113,17 +108,15 @@ static DerivationOutput parseDerivationOutput(const Store & store, istringstream
expect(str, ","); const auto hash = parseString(str);
expect(str, ")");

std::optional<DerivationOutputHash> fsh;
std::optional<FixedOutputHash> fsh;
if (hashAlgo != "") {
auto method = FileIngestionMethod::Flat;
if (string(hashAlgo, 0, 2) == "r:") {
method = FileIngestionMethod::Recursive;
hashAlgo = string(hashAlgo, 2);
}
const HashType hashType = parseHashType(hashAlgo);
if (hashType == htUnknown)
throw Error("unknown hash hashAlgorithm '%s'", hashAlgo);
fsh = DerivationOutputHash {
fsh = FixedOutputHash {
.method = std::move(method),
.hash = Hash(hash, hashType),
};
Expand Down Expand Up @@ -413,17 +406,15 @@ static DerivationOutput readDerivationOutput(Source & in, const Store & store)
auto hashAlgo = readString(in);
const auto hash = readString(in);

std::optional<DerivationOutputHash> fsh;
std::optional<FixedOutputHash> fsh;
if (hashAlgo != "") {
auto method = FileIngestionMethod::Flat;
if (string(hashAlgo, 0, 2) == "r:") {
method = FileIngestionMethod::Recursive;
hashAlgo = string(hashAlgo, 2);
}
const HashType hashType = parseHashType(hashAlgo);
if (hashType == htUnknown)
throw Error("unknown hash hashAlgorithm '%s'", hashAlgo);
fsh = DerivationOutputHash {
fsh = FixedOutputHash {
.method = std::move(method),
.hash = Hash(hash, hashType),
};
Expand Down
Loading