isDelegationValid function

bool 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

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

  // Check the scopes.
  final scopes = <Principal>[];
  final 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 (final s in scopes) {
    final scope = s.toText();
    for (final d in chain.delegations) {
      final delegation = d.delegation;
      if (delegation == null || delegation.targets == null) {
        continue;
      }
      bool none = true;
      final targets = delegation.targets;
      for (final target in targets!) {
        if (target.toText() == scope) {
          none = false;
          break;
        }
      }
      if (none) {
        return false;
      }
    }
  }
  return true;
}