Skip to content

Commit

Permalink
wip: use timestamp for expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
Karl Ranna committed Dec 1, 2020
1 parent 2644404 commit 76c3a11
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 38 deletions.
94 changes: 62 additions & 32 deletions lib/connextclient/ConnextClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
OnchainTransferResponse,
ConnextBlockNumberResponse,
ConnextChannelDetails,
GetBlockByNumberResponse,
} from './types';
import { parseResponseBody } from '../utils/utils';
import { Observable, fromEvent, from, defer, Subscription, throwError, interval, timer } from 'rxjs';
Expand Down Expand Up @@ -185,6 +186,18 @@ class ConnextClient extends SwapClient {

public initSpecific = async () => {
this.on('transferReceived', this.onTransferReceived.bind(this));
/*
setTimeout(async () => {
try {
const blockHeight = await this.getHeight();
const block = await this.getBlockByNumber(blockHeight);
const time = this.parseTimestamp(block.result.timestamp);
console.log('time is', time);
} catch(e) {
console.log('my thing failed', e);
}
}, 2500);
*/
}

private onTransferReceived = async (transferReceivedRequest: TransferReceivedEvent) => {
Expand Down Expand Up @@ -214,13 +227,21 @@ class ConnextClient extends SwapClient {
} = expectedIncomingTransfer;
const currency = this.getCurrencyByTokenaddress(tokenAddress);
const blockHeight = await this.getHeight();
const timelock = expiry - blockHeight;
const block = await this.getBlockByNumber(blockHeight);
const currentTime = this.parseTimestamp(block.result.timestamp);
console.log('currentTime is', currentTime);
const expiryTimestamp = this.parseTimestamp(expiry);
console.log('expiryTimestamp is', expiryTimestamp);
// const timelock = expiry - blockHeight;
// TODO(karl): expiry in this case is block.timestamp so we need to compare it accordingly
// The timelock can be up to 10 blocks less than the agreed upon value
const TIMELOCK_BUFFER = 10;
// const TIMELOCK_BUFFER = 10;
const timelock = 999999;
if (
tokenAddress === expectedTokenAddress &&
units === expectedUnits &&
timelock >= expectedTimelock - TIMELOCK_BUFFER
units === expectedUnits
// TODO(karl): verify the expiryTimestamp and currentTime
// timelock >= expectedTimelock - TIMELOCK_BUFFER
) {
this.logger.debug(`accepting incoming transfer with rHash: ${rHash}, units: ${units}, timelock ${timelock}, currency ${currency}, and routingId ${routingId}`);
this.expectedIncomingTransfers.delete(rHash);
Expand Down Expand Up @@ -437,36 +458,24 @@ class ConnextClient extends SwapClient {
}

public sendSmallestAmount = async (
rHash: string,
destination: string,
currency: string,
) => {
const tokenAddress = this.getTokenAddress(currency);

assert(this.channelAddress, 'cannot send transfer without channel address');
assert(this.publicIdentifier, 'cannot send transfer with channel address');
const expiry = await this.getExpiry(this.finalLock);
await this.executeHashLockTransfer({
type: 'HashlockTransfer',
amount: '1',
assetId: tokenAddress,
details: {
expiry,
lockHash: `0x${rHash}`,
},
recipient: destination,
meta: {
routingId: this.deriveRoutingId(rHash, tokenAddress),
},
channelAddress: this.channelAddress,
publicIdentifier: this.publicIdentifier,
});
return 'sendSmallestAmount is broken';
throw new Error('Connext.sendSmallestAmount is not implemented');
}

private getExpiry = async (locktime: number): Promise<string> => {
private getExpiry = async (locktime: number): Promise<Date> => {
const blockHeight = await this.getHeight();
return (blockHeight + locktime).toString();
const currentBlock = await this.getBlockByNumber(blockHeight);
const currentTime = this.parseTimestamp(currentBlock.result.timestamp);
const locktimeMilliseconds = 15 * locktime * 1000;
console.log('locktimeMilliseconds', locktimeMilliseconds);
const expiry = new Date(currentTime.getTime() + locktimeMilliseconds);
return expiry;
// return currentTime;
/*
const expiry = currentTime.getTime()
return expiry;
*/
// return (blockHeight + locktime).toString();
}

private deriveRoutingId = (lockHash: string, assetId: string): string => {
Expand All @@ -492,7 +501,7 @@ class ConnextClient extends SwapClient {
type: 'HashlockTransfer',
assetId: tokenAddress,
details: {
expiry,
expiry: `${expiry.getTime()}`,
lockHash: `0x${deal.rHash}`,
},
recipient: deal.destination,
Expand Down Expand Up @@ -521,7 +530,7 @@ class ConnextClient extends SwapClient {
type: 'HashlockTransfer',
assetId: tokenAddress,
details: {
expiry,
expiry: `${expiry.getTime()}`,
lockHash: `0x${deal.rHash}`,
},
recipient: deal.destination,
Expand Down Expand Up @@ -719,6 +728,27 @@ class ConnextClient extends SwapClient {
return true;
}

private parseTimestamp = (hexTimestamp: string) => {
console.log('timestampHex of the block is', hexTimestamp);
const timestamp = parseInt(hexTimestamp, 16);
console.log('and after parsing it', timestamp);
const timestampDate = new Date(timestamp);
console.log('this corresponds with', timestampDate);
return timestampDate;
}

private getBlockByNumber = async (blockNumber: number) => {
const res = await this.sendRequest(`/ethprovider/${CHAIN_IDENTIFIERS[this.network]}`, 'POST', {
method: 'eth_getBlockByNumber',
params: [
`0x${blockNumber.toString(16)}`,
false
],
});
const block = await parseResponseBody<GetBlockByNumberResponse>(res);
return block;
}

public getHeight = async () => {
const res = await this.sendRequest(`/ethprovider/${CHAIN_IDENTIFIERS[this.network]}`, 'POST', {
method: 'eth_blockNumber',
Expand Down
33 changes: 29 additions & 4 deletions lib/connextclient/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export type ConnextChannelDetails = {
* The payload for tokenPayment call.
*/
export type ConnextTransferRequest = {
type: 'HashlockTransfer';
type: "HashlockTransfer";
channelAddress: string;
amount: string;
assetId: string;
Expand Down Expand Up @@ -126,6 +126,31 @@ export type ConnextBalanceResponse = {
result: string;
};

export type GetBlockByNumberResponse = {
result: {
difficulty: string;
extraData: string;
gasLimit: string;
gasUsed: string;
hash: string;
logsBloom: string;
miner: string;
mixHash: string;
nonce: string;
number: string;
parentHash: string;
receiptsRoot: string;
sha3Uncles: string;
size: string;
stateRoot: string;
timestamp: string;
totalDifficulty: string;
transactions: string[];
transactionsRoot: string;
uncles: string[];
};
};

/**
* The response for hashLockTransfer call.
*/
Expand All @@ -139,8 +164,8 @@ export type ConnextTransferResponse = {
* The response for withdraw call.
*/
export type ConnextWithdrawResponse = {
channelAddress: '0xa929dB0530daB525596f5d48Fb5C322fDa8A337B';
transferId: '0xc2e4592d3fb6c02ee1d3b07bed83b5914f8ca084b0f91d6b80bf8107e58c9c38';
channelAddress: "0xa929dB0530daB525596f5d48Fb5C322fDa8A337B";
transferId: "0xc2e4592d3fb6c02ee1d3b07bed83b5914f8ca084b0f91d6b80bf8107e58c9c38";
};

type ConnextRoutingPath = {
Expand Down Expand Up @@ -286,7 +311,7 @@ export type ProvidePreimageEvent = {
export type TransferReceivedEvent = {
tokenAddress: string;
rHash: string;
expiry: number;
expiry: string;
units: number;
routingId: string;
};
Expand Down
2 changes: 2 additions & 0 deletions lib/db/seeds/simnet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as db from '../../db/types';
import { SwapClientType } from '../../constants/enums';

const nodes = [
/*
{
nodePubKey: '03ece33a30db1dbce4b62fa96a5e9541138a24997ef5672eebed2d332270e39542',
addresses: [
Expand All @@ -16,6 +17,7 @@ const nodes = [
{ host: 'ri3khz45h25dzxh32z2r7f3s2fgque6f77zygtanldio3z3ps3b3s3id.onion', port: 28885 },
],
},
*/
] as db.NodeAttributes[];

const currencies = [
Expand Down
5 changes: 3 additions & 2 deletions lib/http/HttpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ class HttpService {
} = transfer;
const { routingId } = meta;
const { lockHash, expiry: expiryString } = transferState;
console.log('expiry strin is', expiryString);
const rHash = lockHash.slice(2);
const expiry = parseInt(expiryString, 10);
// const expiry = parseInt(expiryString, 10);
const { amount } = balance;
const units = parseInt(amount[0], 10);
await this.service.transferReceived({
rHash,
expiry,
expiry: expiryString,
units,
routingId,
tokenAddress: assetId,
Expand Down

0 comments on commit 76c3a11

Please sign in to comment.