Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const restartGeth = async () => {
// Restart the validator node
await hooks.restart()
// TODO(mcortesi): magic sleep. without it unlockAccount sometimes fails
await sleep(2)
kit = newKit('http://localhost:8545')
await kit.web3.eth.personal.unlockAccount(validatorAddress, '', 1000)
parameters = await kit.contracts.getBlockchainParameters()
}
export async function initializeKit() {
if (kit === undefined) {
kit = newKit(fetchEnv('CELO_PROVIDER'))
// Copied from @celo/cli/src/utils/helpers
try {
const syncProgress = await kit.web3.eth.isSyncing()
if (typeof syncProgress === 'boolean' && !syncProgress) {
const latestBlock: Block = await kit.web3.eth.getBlock('latest')
if (latestBlock && latestBlock.number > 0) {
// To catch the case in which syncing has happened in the past,
// has stopped, and hasn't started again, check for an old timestamp
// on the latest block
const ageOfBlock = Date.now() / 1000 - latestBlock.timestamp
if (ageOfBlock > 120) {
throw new Error(
`Latest block is ${ageOfBlock} seconds old, and syncing is not currently in progress`
)
}
}
await initAndStartGeth(context.hooks.gethBinaryPath, groupInstance)
allValidators = await getValidatorGroupMembers()
assert.equal(allValidators.length, 5)
epoch = new BigNumber(await validators.methods.getEpochSize().call()).toNumber()
assert.equal(epoch, 10)
// Give the nodes time to sync, and time for an epoch transition so we can activate our vote.
let blockNumber: number
do {
blockNumber = await web3.eth.getBlockNumber()
await sleep(0.1)
} while (blockNumber % epoch !== 1)
await activate(allValidators[0])
const groupWeb3 = new Web3('ws://localhost:8567')
const groupKit = newKitFromWeb3(groupWeb3)
validators = await groupKit._web3Contracts.getValidators()
const membersToSwap = [allValidators[0], allValidators[1]]
let includedMemberIndex = 1
await removeMember(groupWeb3, groupAddress, membersToSwap[0])
const changeValidatorSet = async (header: any) => {
blockNumbers.push(header.number)
// At the start of epoch N, swap members so the validator set is different for epoch N + 1.
if (header.number % epoch === 1) {
const memberToRemove = membersToSwap[includedMemberIndex]
const memberToAdd = membersToSwap[(includedMemberIndex + 1) % 2]
await removeMember(groupWeb3, groupAddress, memberToRemove)
await addMember(groupWeb3, groupAddress, memberToAdd)
includedMemberIndex = (includedMemberIndex + 1) % 2
const newMembers = await getValidatorGroupMembers()
assert.include(newMembers, memberToAdd)
export async function getContractKit(): Promise {
if (contractKit && (await contractKit.isListening())) {
// Already connected
return contractKit
} else {
const httpProvider = new Web3.providers.HttpProvider(WEB3_PROVIDER_URL)
const web3 = new Web3(httpProvider)
contractKit = newKitFromWeb3(web3)
return contractKit
}
}
export const handler = async function autoVerify(argv: AutoVerifyArgv) {
let logger: Logger = createLogger({
name: 'attestation-bot',
serializers: stdSerializers,
streams: [createStream(Level.INFO)],
})
try {
const kit = newKit(argv.celoProvider)
const mnemonic = fetchEnv(envVar.MNEMONIC)
// This really should be the ATTESTATION_BOT key, but somehow we can't get it to have cUSD
const clientKey = ensure0x(
generatePrivateKey(mnemonic, AccountType.ATTESTATION_BOT, argv.index)
)
const clientAddress = privateKeyToAddress(clientKey)
logger = logger.child({ address: clientAddress })
kit.addAccount(clientKey)
const twilioClient = twilio(
fetchEnv(envVar.TWILIO_ACCOUNT_SID),
fetchEnv(envVar.TWILIO_ACCOUNT_AUTH_TOKEN)
)
const attestations = await kit.contracts.getAttestations()
const stableToken = await kit.contracts.getStableToken()
export const simulateClient = async (
senderAddress: string,
recipientAddress: string,
txPeriodMs: number, // time between new transactions in ms
blockscoutUrl: string,
blockscoutMeasurePercent: number, // percent of time in range [0, 100] to measure blockscout for a tx
index: number
) => {
// Assume the node is accessible via localhost with senderAddress unlocked
const kit = newKit('http://localhost:8545')
kit.defaultAccount = senderAddress
const baseLogMessage: any = {
loadTestID: index,
sender: senderAddress,
recipient: recipientAddress,
feeCurrency: '',
txHash: '',
}
while (true) {
const sendTransactionTime = Date.now()
// randomly choose which token to use
const transferGold = Boolean(Math.round(Math.random()))
const transferFn = transferGold ? transferCeloGold : transferCeloDollars
const publicFolderPrefix = `/keybase/public/${username}/`
await this.ensureKeybaseFilePathToProof(publicFolderPrefix)
const fileName = proofFileName(address)
const tmpPath = `${tmpdir()}/${fileName}`
writeFileSync(tmpPath, JSON.stringify(signedClaim))
await execCmdWithError(
'keybase',
['fs', 'cp', tmpPath, publicFolderPrefix + keybaseFilePathToProof + '/' + fileName],
{ silent: true }
)
cli.action.stop()
cli.action.start(`Claim successfully copied to the keybase file system, verifying proof`)
// Wait for changes to propagate
await sleep(3000)
const verificationError = await verifyKeybaseClaim(claim, address)
if (verificationError) {
throw new Error(`Claim is not verifiable: ${verificationError}`)
}
cli.action.stop()
console.info('Claim is verifiable!')
} catch (error) {
cli.action.stop(`Error: ${error}`)
throw error
}
}
async uploadProof(claim: KeybaseClaim, signature: string, username: string, address: string) {
// if (currentNumber !== 727) {
// throw new Error(`Expected current number to be 727, but was ${currentNumber}`)
// }
// Example B: Repoint a Celo Core Contract proxy
const validatorsProxyAddress = await kit.registry.addressFor(CeloContract.Validators)
const currentValidatorsImplementationAddress = await getImplementationOfProxy(
kit.web3,
validatorsProxyAddress
)
const desiredImplementationAddress = '0xd18620a5eBE0235023602bB4d490E1e96703EddD'
console.info('Current Implementation Address: ', currentValidatorsImplementationAddress)
console.info('\nBuild Proposal')
const proposalBuilder = new ProposalBuilder(kit)
// Example A
// proposalBuilder.addJsonTx({
// contract: CeloContract.Attestations,
// function: 'setAttestationExpiryBlocks',
// // @ts-ignore
// args: [728],
// value: '0',
// })
// Example B
proposalBuilder.addProxyRepointingTx(validatorsProxyAddress, desiredImplementationAddress)
const proposal = await proposalBuilder.build()
const proposalHash = proposalToHash(kit, proposal)
console.info('Add keys to ContractKit')
for (const key of keys) {
kit.addAccount(key)
}
// Here you'll want to assert the current state
// Example A: Update a var on a Celo Core Contract
// const attestations = await kit.contracts.getAttestations()
// const currentNumber = await attestations.attestationExpiryBlocks()
// if (currentNumber !== 727) {
// throw new Error(`Expected current number to be 727, but was ${currentNumber}`)
// }
// Example B: Repoint a Celo Core Contract proxy
const validatorsProxyAddress = await kit.registry.addressFor(CeloContract.Validators)
const currentValidatorsImplementationAddress = await getImplementationOfProxy(
kit.web3,
validatorsProxyAddress
)
const desiredImplementationAddress = '0xd18620a5eBE0235023602bB4d490E1e96703EddD'
console.info('Current Implementation Address: ', currentValidatorsImplementationAddress)
console.info('\nBuild Proposal')
const proposalBuilder = new ProposalBuilder(kit)
// Example A
// proposalBuilder.addJsonTx({
// contract: CeloContract.Attestations,
// function: 'setAttestationExpiryBlocks',
// // @ts-ignore
const proposalBuilder = new ProposalBuilder(kit)
// Example A
// proposalBuilder.addJsonTx({
// contract: CeloContract.Attestations,
// function: 'setAttestationExpiryBlocks',
// // @ts-ignore
// args: [728],
// value: '0',
// })
// Example B
proposalBuilder.addProxyRepointingTx(validatorsProxyAddress, desiredImplementationAddress)
const proposal = await proposalBuilder.build()
const proposalHash = proposalToHash(kit, proposal)
// If your proposal is just made of ContractKit methods, you can print it out
// console.info('Proposal: ', await proposalToJSON(kit, proposal))
console.info(`Proposal Hash: ${proposalHash.toString('hex')}`)
console.info('\nWhitelist the hotfix')
await concurrentMap(25, addresses, async (address, index) => {
try {
await governance.whitelistHotfix(proposalHash).sendAndWaitForReceipt({ from: address })
} catch (error) {
console.error(`Error whitelisting for validator ${index} (${address}): ${error}`)
}
})
let hotfixRecord = await governance.getHotfixRecord(proposalHash)