isDelegationValid function

dynamic isDelegationValid(
  1. DelegationChain chain,
  2. DelegationValidChecks? checks
)

Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the scope. @param chain The chain to validate. @param checks Various checks to validate on the chain.

Implementation

isDelegationValid(DelegationChain chain, DelegationValidChecks? checks) {
  // Verify that the no delegation is expired. If any are in the chain, returns false.
  for (var d in chain.delegations) {
    var delegation = d.delegation!;
    var exp = delegation.expiration;
    var t = exp / BigInt.from(1000000);
    // prettier-ignore
    if (DateTime.fromMillisecondsSinceEpoch(t.toInt())
        .isBefore(DateTime.now())) {
      return false;
    }
  }

  // Check the scopes.
  var scopes = <Principal>[];

  var maybeScope = checks?.scope;

  if (maybeScope != null) {
    if (maybeScope is List) {
      scopes.addAll(maybeScope
          .map((s) => (s is String ? Principal.fromText(s) : (s as Principal)))
          .toList());
    } else {
      scopes.addAll(
          maybeScope is String ? Principal.fromText(maybeScope) : maybeScope);
    }
  }

  for (var s in scopes) {
    var scope = s.toText();
    for (var d in chain.delegations) {
      var delegation = d.delegation;
      if (delegation == null || delegation.targets == null) {
        continue;
      }

      var none = true;
      var targets = delegation.targets;
      for (var target in targets!) {
        if (target.toText() == scope) {
          none = false;
          break;
        }
      }
      if (none) {
        return false;
      }
    }
  }

  return true;
}