Skip to content
This repository has been archived by the owner on Nov 24, 2022. It is now read-only.

Commit

Permalink
Anticov delegation setup button (#266)
Browse files Browse the repository at this point in the history
Adds a button that invites your currently selected identity to the AntiCov delegation tree and directly imports the new delegation. If the ctype and delegation root for AntiCov do not yet exists on chain, they will be created and registered.

Co-authored-by: dudleyneedham <dudleyneedham1993@gmail.com>
  • Loading branch information
rflechtner and Dudleyneedham authored Jun 4, 2020
1 parent 5627a7b commit f12917b
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 18 deletions.
102 changes: 102 additions & 0 deletions src/components/DevTools/DevTools.anticov.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import * as sdk from '@kiltprotocol/sdk-js'
import { IMetadata } from '@kiltprotocol/sdk-js/build/types/CTypeMetadata'
import {
ROOT_SEED,
CTYPE,
CTYPE_METADATA,
DELEGATION_ROOT_ID,
} from './data/anticov.json'
import { IMyIdentity } from '../../types/Contact'
import CTypeRepository from '../../services/CtypeRepository'
import { BalanceUtilities } from '../../services/BalanceUtilities'
import MessageRepository from '../../services/MessageRepository'
import DelegationsService from '../../services/DelegationsService'
import FeedbackService, {
notifySuccess,
notifyFailure,
} from '../../services/FeedbackService'

const root = sdk.Identity.buildFromMnemonic(ROOT_SEED)

const ctype = sdk.CType.fromCType(CTYPE as sdk.ICType)
ctype.owner = root.address
const metadata: IMetadata = CTYPE_METADATA

const delegationRoot = new sdk.DelegationRootNode(
DELEGATION_ROOT_ID,
ctype.hash,
root.address
)

async function newDelegation(delegate: IMyIdentity): Promise<void> {
const delegationNode = new sdk.DelegationNode(
sdk.UUID.generate(),
delegationRoot.id,
delegate.identity.address,
[sdk.Permission.ATTEST]
)
const signature = delegate.identity.signStr(delegationNode.generateHash())
await delegationNode.store(root, signature)
notifySuccess(`Delegation successfully created for ${delegate.metaData.name}`)
await DelegationsService.importDelegation(
delegationNode.id,
'AntiCov Attester',
false
)
notifySuccess(`Delegation imported. Switch to Delegation Tab to see it.`)
const messageBody: sdk.MessageBody = {
type: sdk.MessageBodyType.INFORM_CREATE_DELEGATION,
content: { delegationId: delegationNode.id, isPCR: false },
}
await MessageRepository.sendToAddresses(
[delegate.identity.address],
messageBody
)
}

async function verifyOrAddCtypeAndRoot(): Promise<void> {
if (!(await ctype.verifyStored())) {
await ctype.store(root)
CTypeRepository.register({
cType: ctype,
metaData: { metadata, ctypeHash: ctype.hash },
})
notifySuccess(`CTYPE ${metadata.title.default} successfully created.`)
}
// delegationRoot.verify() is unreliable when using the currently released mashnet-node & sdk
// workaround is checking the ctype hash of the query result; it is 0x000... if it doesn't exist on chain
const queriedRoot = await sdk.DelegationRootNode.query(delegationRoot.id)
if (queriedRoot?.cTypeHash !== ctype.hash) {
await delegationRoot.store(root)
const messageBody: sdk.MessageBody = {
type: sdk.MessageBodyType.INFORM_CREATE_DELEGATION,
content: { delegationId: delegationRoot.id, isPCR: false },
}
notifySuccess(`AntiCov Delegation Root successfully created.`)
// sending root owner message for importing the root
const message = new sdk.Message(messageBody, root, root)
await MessageRepository.dispatchMessage(message)
notifySuccess(`Sent Delegation Root to AntiCov root authority.`)
}
}

export async function setupAndDelegate(delegate: IMyIdentity): Promise<void> {
const blockUi = FeedbackService.addBlockUi({
headline: 'Creating AntiCov Delegation',
})
try {
blockUi.updateMessage('Transferring funds to AntiCov authority')
await new Promise(resolve => {
BalanceUtilities.makeTransfer(delegate, root.address, 4, () => resolve())
})
blockUi.updateMessage('Setting up CType and Root Delegation')
await verifyOrAddCtypeAndRoot()
blockUi.updateMessage('Creating Delegation Node for current identity')
await newDelegation(delegate)
} catch (error) {
notifyFailure(`Failed to set up Delegation Node: ${error}`)
}
blockUi.remove()
}

export default setupAndDelegate
10 changes: 10 additions & 0 deletions src/components/DevTools/DevTools.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'

import setupAndDelegate from './DevTools.anticov'
import {
ENDOWMENT,
MIN_BALANCE,
Expand Down Expand Up @@ -160,6 +161,15 @@ class DevTools extends React.Component<Props> {
</button>
))}
</div>
<div>
<h4>AntiCov Setup</h4>
<button
type="button"
onClick={() => setupAndDelegate(selectedIdentity)}
>
AntiCov Delegation
</button>
</div>
{withMessages.map((messages: WithMessages) => (
<div key={messages.label}>
<h4>{`Manual Bootstrap ${messages.label}`}</h4>
Expand Down
34 changes: 34 additions & 0 deletions src/components/DevTools/data/anticov.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"CTYPE": {
"schema": {
"$id": "anticov",
"$schema": "http://kilt-protocol.org/draft-01/ctype#",
"properties": {
"photo": {
"type": "string"
}
},
"type": "object"
},
"hash": "0x005db4d03c57d15c47083cd363311669f0543e5647e26da1c5f12fe4fa8cd84d",
"owner": "5Gtn4ZBVeqndGwt41AntNgSDCSBcsiyFr3NAm77UDGXbgxva"
},
"CTYPE_METADATA": {
"title": {
"default": "AntiCov"
},
"description": {
"default": "AntiCov Ctype"
},
"properties": {
"photo": {
"title": {
"default": "photo"
},
"description": {}
}
}
},
"DELEGATION_ROOT_ID": "0x36656438633364382d393431372d346563392d386263612d3163646136346438",
"ROOT_SEED": "attract follow jealous bamboo document wine object edit cave mechanic clap flavor"
}
4 changes: 2 additions & 2 deletions src/services/BalanceUtilities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ class BalanceUtilities {
)
}

private static asKiltCoin(balance: BN): number {
public static asKiltCoin(balance: BN): number {
return balance.divn(KILT_MICRO_COIN).toNumber()
}

private static asMicroKilt(balance: number): BN {
public static asMicroKilt(balance: number): BN {
return new BN(balance).muln(KILT_MICRO_COIN)
}
}
Expand Down
18 changes: 13 additions & 5 deletions src/services/DelegationsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,28 @@ class DelegationsService {
if (delegation) {
const root = await delegation.getRoot()
const myDelegation: Delegations.IMyDelegation = {
account: delegation.account,
...delegation,
cTypeHash: root && root.cTypeHash,
id: delegation.id,
isPCR,
metaData: { alias },
parentId: delegation.parentId,
permissions: delegation.permissions,
revoked: false,
rootId: delegation.rootId,
type: Delegations.DelegationType.Node,
}
DelegationsService.store(myDelegation)
return myDelegation
}
const root = await DelegationsService.lookupRootNodeById(delegationNodeId)
if (root) {
const myDelegation: Delegations.IMyDelegation = {
...root,
isPCR,
metaData: { alias },
revoked: false,
type: Delegations.DelegationType.Root,
}
DelegationsService.store(myDelegation)
return myDelegation
}
return null
}

Expand Down
23 changes: 12 additions & 11 deletions src/services/MessageRepository.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,17 @@ class MessageRepository {
})
}

public static async dispatchMessage(message: sdk.Message): Promise<Response> {
const response = await fetch(`${MessageRepository.URL}`, {
...BasePostParams,
body: JSON.stringify(message.getEncryptedMessage()),
})
if (!response.ok) {
throw new Error(response.statusText)
}
return response
}

public static async singleSend(
messageBody: sdk.MessageBody,
sender: IMyIdentity,
Expand All @@ -207,17 +218,7 @@ class MessageRepository {

message = await MessageRepository.handleDebugMode(message)

return fetch(`${MessageRepository.URL}`, {
...BasePostParams,
body: JSON.stringify(message.getEncryptedMessage()),
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response
})
.then(response => response.json())
return MessageRepository.dispatchMessage(message)
.then(() => {
notifySuccess(
`Message '${messageBody.type}' to receiver ${receiver.metaData
Expand Down

0 comments on commit f12917b

Please sign in to comment.