Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirKeys extends Event
/**
* Voting round: the social-recovery guard; refuses a `read` key (or stake
* 9000) and any signer that is not the identity's stake-100 key
* ("Incorrect Signing Key"); then checkKeyExpire on the key being added.
*
* @returns {Promise<boolean>}
* @memberof VarnirKeys
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
//this.hasAuthorityStake(100, owner)
// hasAuthority also manging it wrong for this
const owner = this.getActivityStreams(this.transactions.$i.owner);
const currentAuth = (this as any).sigs[owner.getId()];
// A tenant's master and shard streams are not identities (Varnir.Tenants owns them): their keys are not
// edited here, whoever signs. Otherwise a tenant could strip Varnir's sweeper authority from its shards.
const ownerKind = (owner.getState() as any)?.kind;
if (typeof ownerKind === "string" && ownerKind.indexOf("varnir.tenant") === 0) {
return reject("Keys - this stream is not an identity (a tenant's streams are managed by Varnir.Tenants)");
}
// Global check for read only customer service. Role is the key's LABEL,
// never its stake (stake is consensus weight only). The stake-100 signer
// check below independently bars non-owners; this gives the clear message
// and keeps the read-only gate atomic with the other contracts.
if (this.signingKeyLabel(owner) === "read" || this.hasAuthorityStake(9000, owner)) {
return reject("Stake Permission Error - Read Only 9000");
}
// We will only have 1 signature
const currentAuthKeys = Object.keys(currentAuth);
if (
!owner.getAuthorities().some((authority) => {
return (
authority.stake === 100 && authority.hash === currentAuthKeys[0]
);
})
) {
return reject("Incorrect Signing Key");
}
// Authority expiry (Activeledger 4.8.0+, enforced once the network
// build reaches 40100). Refused in vote(), the same round
// Varnir.CryptoTransfer refuses an out-of-date proposal in, so a bad
// lifetime never reaches commit() and never reaches a stored authority.
const expiryRefusal = this.checkKeyExpire(owner);
if (expiryRefusal) {
return reject(expiryRefusal);
}
resolve(true);
});
}/**
* Commit round: records the umid in the volatile's `keyUmids` (carrying
* over and dropping the legacy `BPKeyUmids` list), writes
* `requiresTreasury`, then applies `add` and `remove` as described on the
* class.
*
* @returns {Promise<any>}
* @memberof VarnirKeys
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
const owner = this.getActivityStreams(this.transactions.$i.owner);
const state = owner.getState();
// Add this to volatile for proof of key add/removal
const ownerVolatile = await owner.getVolatile();
// Renamed from BPKeyUmids along with the contract itself. Identities
// onboarded before that rename still carry the old field, so the first
// write here carries its entries across and drops it: the audit trail
// stays continuous and there is no migration pass to run beforehand.
// The old name is read, never written - once an identity has been
// through here it no longer has one.
if (!ownerVolatile.keyUmids) {
ownerVolatile.keyUmids = ownerVolatile.BPKeyUmids
? ownerVolatile.BPKeyUmids
: [];
}
if (ownerVolatile.BPKeyUmids) {
delete ownerVolatile.BPKeyUmids;
}
ownerVolatile.keyUmids.push(this.umid);
owner.setVolatile(ownerVolatile);
// Generic Limits
if (this.transactions.$i.owner.treasury) {
state.requiresTreasury = this.transactions.$i.owner.treasury;
owner.setState(state);
}
// Adding a Key
if (this.transactions.$i.owner.add) {
// Treasure Switch
if (this.transactions.$i.owner.treasury) {
// Both verify. The label is what separates them, and
// Varnir.CryptoTransfer reads it back off the signing authority:
//
// treasury dual status - may raise transfers as well as confirm
// verifier confirms only; its own sends are refused
//
// Neither may confirm a proposal it raised itself; that is enforced
// separately, by key hash, and applies to both.
owner.setAuthorities(
this.newAuthority(
80,
this.transactions.$i.owner.verifyOnly ? "verifier" : "treasury"
)
);
// Set this flag to pickup on needing >80 stake check
state.hasTreasury = this.ActiveCrypto.Hash.getHash(this.transactions.$i.owner.add.public, "sha256");
} else if (this.transactions.$i.owner.read) {
// Adding a Key
owner.setAuthorities(this.newAuthority(0, "read"));
} else if (this.transactions.$i.owner.offledger) {
// Off-ledger key: zero on-ledger signing power (stake 0, same as
// "secondary"), but carries a set of off-ledger permission scopes
// in the (currently inert) restrictions slot for a consumer such
// as minigate to read later. No `policy` is written here.
owner.setAuthorities(this.newAuthority(0, "offledger"));
if (!state.restrictions) {
state.restrictions = {};
}
state.restrictions[
this.ActiveCrypto.Hash.getHash(
this.transactions.$i.owner.add.public
)
] = {
version: 1,
scopes: this.transactions.$i.owner.scopes ?? [],
};
} else {
// Adding a Key
owner.setAuthorities(this.newAuthority(0, "secondary"));
}
if (this.transactions.$i.owner.restrictions) {
if (!state.restrictions) {
state.restrictions = {};
}
// Make it so that we can reuse the hash
state.restrictions[
this.ActiveCrypto.Hash.getHash(
this.transactions.$i.owner.add.public
)
] = this.transactions.$i.owner.restrictions;
}
if (this.transactions.$i.owner.apiKey) {
state.apiKey = this.transactions.$i.owner.apiKey;
}
owner.setState(state);
}
if (this.transactions.$i.owner.remove) {
// Removal of treausry limits
// if (this.transactions.$i.owner.treasury && !this.transactions.$i.owner.add) {
// state.requiresTreasury = null;
// state.hasTreasury = null;
// }
this.ActiveLogger.warn(this.transactions.$i.owner, "Removing Stake != 100 3.00" + this.umid);
owner.deleteAuthorities((authority) => {
return (
authority.stake !== 100 &&
authority.public === this.transactions.$i.owner.remove
);
});
// Removal of treausry limits
if (this.transactions.$i.owner.treasury && !this.transactions.$i.owner.add) {
const authorities = (owner as any).meta.authorities;
if(!authorities.some(a => a.label === 'treasury' && a.stake === 80)) {
state.requiresTreasury = null;
state.hasTreasury = null;
}
}
if (state.restrictions) {
if (
state.restrictions[
this.ActiveCrypto.Hash.getHash(this.transactions.$i.owner.remove)
]
) {
delete state.restrictions[
this.ActiveCrypto.Hash.getHash(this.transactions.$i.owner.remove)
];
}
}
owner.setState(state);
}
resolve(true);
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
}/**
* The authority record this transaction attaches, built FIELD BY FIELD.
*
* This was `{...this.transactions.$i.owner.add, stake, label}`. A spread
* writes whatever the caller put in `add` straight onto a stored authority,
* so any field the ENGINE later grows a meaning for arrives unvalidated and
* takes effect - `expire` was exactly that field, live and enforced before
* this contract knew it existed. Every producer in this repo
* (packages/chain-client's `addKey`, apps/wallet-mobile's port of it) sends
* `public` and `type` and nothing else, so naming them costs nothing and
* closes the hole.
*
* `hash` and `umid` are deliberately NOT taken from the caller: Activeledger's
* own setAuthorities stamps both, and a caller-supplied `hash` would decide
* which existing authority this record REPLACES (it dedupes by hash).
*/ private newAuthority(stake: number, label: string): any {
const add = this.transactions.$i.owner.add;
const authority: any = {
public: add.public,
type: add.type,
stake,
label,
};
// Written only once vote()'s checkKeyExpire has passed it. Set rather
// than always present because ABSENT MEANS NEVER EXPIRES - the engine's
// own rule - and an `expire: undefined`/`null` sitting on the record
// would read as "expiring" to the engine's hasNonExpiringAuthority.
if (typeof add.expire === "string" && add.expire) {
authority.expire = add.expire;
}
return authority;
}/** * The refusal string for an unsafe `expire` on the key being added, or null * when there is nothing to refuse. * * ABSENT MEANS NEVER EXPIRES. The engine fails open here deliberately * (`isAuthorityExpired` returns false for an authority with no `expire`), * so this whole check only runs when a caller actually asked for a lifetime. * Note this is the OPPOSITE convention to Varnir.CryptoTransfer's proposal * `expiresAt`, where a missing value reads as already expired - that one * guards a pre-authorised payment and must fail closed; this one guards a * key's existence and must not lapse keys nobody dated. */
private checkKeyExpire(owner: any): string | null {
const add = this.transactions.$i.owner.add;
if (!add) {
return null;
}
const expire = add.expire;
if (expire === undefined || expire === null) {
return null;
}
if (typeof expire !== "string" || !AUTHORITY_EXPIRE_ISO.test(expire)) {
return "Key Expiry Invalid - expire must be an absolute ISO 8601 instant with an explicit zone, e.g. 2030-01-01T00:00:00Z";
}
// CONSENSUS CLOCK ONLY. this.cDate is the per-transaction consensus
// timestamp, identical on every node; new Date(this.cDate) merely READS
// it. Date.now()/new Date() here would let two nodes vote differently on
// the same transaction. It is also the value the engine itself compares
// against - entry.$datetime IS this - so contract and engine agree on
// when "now" is.
const expireAt = new Date(expire).getTime();
if (Number.isNaN(expireAt)) {
return "Key Expiry Invalid - expire is not a real date";
}
// <=, not <: the engine treats an authority whose expire equals the
// transaction time as ALREADY expired (isAuthorityExpired uses <=), so a
// key written at exactly this instant could never sign anything.
if (expireAt <= new Date(this.cDate).getTime()) {
return "Key Expiry Invalid - expire must be in the future";
}
const authorities = owner.getAuthorities() || [];
const addHash = this.ActiveCrypto.Hash.getHash(add.public, "sha256");
// Adding a key whose hash already belongs to an authority REPLACES that
// authority: Activeledger's setAuthorities dedupes by hash, last write
// winning. So an "add" is also a rewrite, and both refusals below are
// about what that rewrite would destroy - not merely about the new row.
const replaces = (authority: any) =>
authority.hash === addHash || authority.public === add.public;
// The owner key is the recovery path. An expiring owner is how an identity
// becomes permanently unrecoverable: once the only stake-100 authority has
// lapsed nothing can re-key it, because re-keying is itself owner-signed.
// Refused outright rather than validated.
if (
authorities.some(
(authority: any) => authority.stake === 100 && replaces(authority)
)
) {
return "Key Expiry Refused - the owner key cannot be given an expiry";
}
// The lockout invariant, enforced here so the caller learns WHICH key
// caused it. The engine enforces the same rule twice - setAuthorities
// throws "Operation denied this would expire every authority", and commit
// raises 1236 "would have no permanent authority" - but neither message
// names a key, so a caller seeing one cannot act on it.
//
// PERMANENT means NO `expire` FIELD AT ALL, matching the engine's own
// hasNonExpiringAuthority. A far-future expiry does NOT count. The record
// being added always carries one, so the surviving authorities are the
// only place a permanent key can come from.
const surviving = authorities.filter(
(authority: any) => !replaces(authority)
);
if (!surviving.some((authority: any) => authority.expire === undefined)) {
return "Key Expiry Refused - this is the identity's last authority without an expiry, and every authority expiring would lock the identity out";
}
return null;
}/** The hash of the key that signed for `owner` (the first key in `sigs[owner]`), or null. */
private signingKeyHash(owner: any): string | null {
const currentAuth = (this as any).sigs?.[owner.getId()];
if (!currentAuth) {
return null;
}
const keys = Object.keys(currentAuth);
return keys.length ? keys[0] : null;
}/** The label on the authority that signed for `owner`, lower-cased and trimmed, or null. */
private signingKeyLabel(owner: any): string | null {
const hash = this.signingKeyHash(owner);
if (!hash) {
return null;
}
const authority = owner
.getAuthorities()
.find((candidate: any) => candidate.hash === hash);
const label = authority?.label;
return label ? String(label).toLowerCase().trim() : null;
}