Skip to content

Commit

Permalink
reapply changes from reverted commit "update some test;fix issue1;fix…
Browse files Browse the repository at this point in the history
… pr ontio#7 (ontio#8)"

Signed-off-by: Matus Zamborsky <zamborsky@gmail.com>
  • Loading branch information
backslash47 committed Apr 7, 2018
1 parent 36f6402 commit 6921dcf
Show file tree
Hide file tree
Showing 23 changed files with 279 additions and 145 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
"main": "./lib/index.js",
"types": "./lib/types/index.d.ts",
"scripts": {
"test": "jest",
"build:dev": "webpack --display-error-details --config webpack.config.js --progress --color",
"build:prod": "webpack --env.prod --config webpack.config.js --progress --color"
"test": "./node_modules/.bin/jest",
"build:dev": "./node_modules/.bin/webpack --display-error-details --config webpack.config.js --progress --color",
"build:prod": "./node_modules/.bin/webpack --env.prod --config webpack.config.js --progress --color"
},
"jest": {
"moduleFileExtensions": [
Expand Down
2 changes: 1 addition & 1 deletion src/claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class Claim {
this.Id = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(JSON.stringify(body))).toString()
}

sign( privateKey: string ) {
sign( privateKey: string ) : Signature {
let claimBody = {
Context: this.Context,
Id: this.Id,
Expand Down
2 changes: 1 addition & 1 deletion src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class Algorithm {
export const DEFAULT_ALGORITHM = {
algorithm : "ECDSA",
parameters : {
"curve": "secp256r1"
"curve": "secp256r1" // also called p256
}
}

Expand Down
44 changes: 37 additions & 7 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import * as base58 from 'bs58'
import * as ecurve from 'ecurve'
import * as bigInteger from 'bigi'
import { ab2hexstring, hexstring2ab, StringReader, hexstr2str, num2hexstring } from './utils'
import { ADDR_VERSION } from './consts'
import { ADDR_VERSION, TEST_ONT_URL } from './consts'
import * as scrypt from './scrypt'
import {ERROR_CODE} from './error'
import { VmType } from './transaction/vmcode';
import { buildGetDDOTx, buildRestfulParam, sendRawTxRestfulUrl} from './transaction/transactionBuilder'
import axios from 'axios'
import { DDO } from './transaction/ddo'

var ec = require('elliptic').ec
var wif = require('wif')
Expand Down Expand Up @@ -147,12 +150,20 @@ export function signatureData(data: string, privateKey: string): string {
return signatureValue.toString('hex');
}

export function verifySignature(data : string, signature : string, publicKey : string) {

/*
@data original value of signature
@signature
@publicKey the public key of the signer. is array-like or buffer
*/
export function verifySignature(data: string, signature: string, publicKey: any) {
let msg = cryptoJS.enc.Hex.parse(data)
let msgHash = cryptoJS.SHA256(msg)

let elliptic = new ec('p256')
const result = elliptic.verify(data.toString(), signature, publicKey, null)
let r = signature.substr(0, 64)
let s = signature.substr(64, 64)
const result = elliptic.verify(msgHash.toString(), { r, s }, publicKey, null)
return result
}

Expand Down Expand Up @@ -212,11 +223,30 @@ export function checkPrivateKey(encryptedPrivateKey : string, password : string)
return true
}


/*
@claim claim json object
*/
export function verifyOntidClaim(claim : any) {
if(!claim.Metadata || !claim.Metadata.Issuer) {
throw new Error('Invalid claim.')
}
let issuer = claim.Metadata.Issuer
//TODO
}
let issuerDid = claim.Metadata.Issuer
let tx = buildGetDDOTx(issuerDid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
return axios.post(url, param).then( (res:any) => {
if (res.data.Result && res.data.Result.length > 0) {
console.log('ddo hexstr: '+ res.data.Result[0])
const ddo = DDO.deserialize(res.data.Result[0])
console.log('ddo: ' + JSON.stringify(ddo))
if(ddo.publicKeys.length > 0) {
const pk = ddo.publicKeys[0].pk
const signature = claim.Signature.Value
claim.delete('Signature')
return verifySignature(JSON.stringify(claim), signature, hexstring2ab(pk))
} else {
return false
}
}
})
}
23 changes: 23 additions & 0 deletions src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,26 @@ export enum SignatureSchema {

SHA512withEDDSA
}

export enum CurveLabel {
P224 = 1,
P256 = 2,
P384 = 3,
P521 = 4,

SM2P256V1 = 20,

ED25519 = 25
}

export enum KeyType {
PK_ECDSA = 0x12,
PK_SM2 = 0x13,
PK_EDDSA = 0x14,
}

export class PublicKey {
algorithm: number
curve: number
pk: string
}
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import * as core from './core'
import * as utils from './utils'
import * as CONST from './consts'
import { SDK } from './sdk/index'
import { CompleterResult } from 'readline';

class ONT {
Account : any
Expand Down Expand Up @@ -81,7 +80,7 @@ class ONT {
this.CONST.HTTP_REST_PORT = port
}

setWsPortyarn(port: string) {
setSocketPort(port: string) {
this.CONST.HTTP_WS_PORT = port
}
}
Expand Down
60 changes: 44 additions & 16 deletions src/sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,33 @@ import axios from 'axios'
import {BigNumber} from 'bignumber.js'
import {DDO} from '../transaction/ddo';
export class SDK {
static SERVER_NODE : string
static REST_PORT : string
static SOCKET_PORT : string

static setServerNode(node : string) {
if(node) {
SDK.SERVER_NODE = node
return;
}
throw new Error('Can not set ' + node + 'as server node')
}

static setRestPort(port: string) {
if (port) {
SDK.REST_PORT = port
return;
}
throw new Error('Can not set ' + port + ' as restful port')
}

static setSocketPort(port: string) {
if (port) {
SDK.SOCKET_PORT = port
return;
}
throw new Error('Can not set ' + port + 'as socket port')
}

static getDecryptError(err:any) {
return {
Expand Down Expand Up @@ -80,7 +107,8 @@ export class SDK {
socket.close()
}
}
var txSender = new TxSender(ONT_NETWORK.TEST)
let socket = `ws://${SDK.SERVER_NODE}:${SDK.SOCKET_PORT}`
var txSender = new TxSender(socket)
txSender.sendTxWithSocket(param, socketCallback)
// callback && sendBackResult2Native(JSON.stringify(obj), callback)
return obj
Expand All @@ -90,10 +118,8 @@ export class SDK {
password : string, callback ?: string) {
let identity = new Identity()
let wallet = Wallet.parseJson(walletDataStr)
let privateKey = ''
try {
//TODO check ontid
privateKey = scrypt.decrypt(encryptedPrivateKey, password)
identity = Identity.importIdentity(label, encryptedPrivateKey, password)
} catch (err) {
let obj = this.getDecryptError(err)
Expand All @@ -109,9 +135,10 @@ export class SDK {
desc : ''
}
//check ontid on chain
let tx = buildGetDDOTx(identity.ontid, privateKey)
let tx = buildGetDDOTx(identity.ontid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}/`
let url = sendRawTxRestfulUrl(restUrl, true)
axios.post(url, param).then((res:any) => {
if (res.data.Result && res.data.Result.length > 0 && res.data.Result[0] !== '0000000000000000') {

Expand All @@ -130,9 +157,7 @@ export class SDK {
static importIdentity(label : string, encryptedPrivateKey : string, password : string, callback ?: string) {
let identity = new Identity()
let error = {}
let privateKey
try {
privateKey = scrypt.decrypt(encryptedPrivateKey, password)
identity = Identity.importIdentity(label, encryptedPrivateKey, password)
let wallet = new Wallet()
wallet.create(identity.label)
Expand All @@ -145,10 +170,11 @@ export class SDK {
desc: ''
}
//check ontid on chain
let tx = buildGetDDOTx(identity.ontid, privateKey)
let tx = buildGetDDOTx(identity.ontid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
axios.post(url, param).then((res: any) => {
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}/`
let url = sendRawTxRestfulUrl(restUrl, true)
return axios.post(url, param).then((res: any) => {
if (res.data.Result && res.data.Result.length > 0 && res.data.Result[0] !== '0000000000000000') {

} else {
Expand All @@ -163,7 +189,7 @@ export class SDK {
} catch(err) {
error = this.getDecryptError(err)
callback && sendBackResult2Native(JSON.stringify(error), callback)
return error
return Promise.reject(error)
}
}

Expand All @@ -180,8 +206,9 @@ export class SDK {
//register ontid
let tx = buildRegisterOntidTx(identity.ontid, privateKey)
let param = buildRestfulParam(tx)
const url = TEST_ONT_URL.sendRawTxByRestful
axios.post(url, param).then((res: any) => {
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.sendRawTx}`

axios.post(restUrl, param).then((res: any) => {
if(res.data.Error === 0) {
callback && sendBackResult2Native(JSON.stringify(obj), callback)
} else {
Expand Down Expand Up @@ -322,7 +349,8 @@ export class SDK {
// let txId = core.getHash(tx.serialize())
let param = buildTxParam(tx)
//通过socket能获得推送的结果
var txSender = new TxSender(ONT_NETWORK.TEST)
let socket = `ws://${SDK.SERVER_NODE}:${SDK.SOCKET_PORT}`
var txSender = new TxSender(socket)
const socketCallback = function(res : any, socket : any) {
console.log('res: '+ JSON.stringify(res))
if(res.Action === 'InvokeTransaction' && res.Error === 0) {
Expand Down Expand Up @@ -365,7 +393,7 @@ export class SDK {
if(address.length === 40) {
address = core.u160ToAddress(address)
}
let request = `http://${TEST_NODE}:${HTTP_REST_PORT}${REST_API.getBalance}/${address}`
let request = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.getBalance}/${address}`
axios.get(request).then((res : any) => {
if(res.data.Error === 0) {
let result = res.data.Result
Expand Down Expand Up @@ -423,7 +451,7 @@ export class SDK {

let tx = makeTransferTransaction('ONT',from, to, value, privateKey)
var param = buildRestfulParam(tx)
let request = `http://${TEST_NODE}:${HTTP_REST_PORT}${REST_API.sendRawTx}`
let request = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.sendRawTx}`
axios.post(request, param).then( (res:any) => {
console.log('transfer response: ' + JSON.stringify(res.data))
if(res.data.Error === 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/smartcontract/data/idContract.abi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default {
"hash": "80e7d2fc22c24c466f44c7688569cc6e6d6c6f92",
"hash": "80a45524f3f6a5b98d633e5c7a7458472ec5d625",
"entrypoint": "Main",
"functions":
[
Expand Down
67 changes: 45 additions & 22 deletions src/transaction/ddo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

import {StringReader, hexstr2str} from '../utils'
import {PublicKey} from '../crypto'

export class DDOAttribute {
path : string
Expand All @@ -25,42 +26,64 @@ export class DDOAttribute {
constructor() {}
}
export class DDO {
publicKeys : Array<string> = []
publicKeys : Array<PublicKey> = []
attributes : Array<DDOAttribute> = []
recovery : string

constructor() {}

static deserialize(hexstr : string) : DDO {
static deserialize(hexstr: string): DDO {
const ss = new StringReader(hexstr)
let ddo = new DDO()
//total length of public keys - 4 bytes
const pkTotalLen = parseInt(ss.read(4), 16)
const pkNum = ss.readNextLen()

for(let i=0; i<pkNum; i++) {
//length of public key - 4 bytes
let pkLen = parseInt(ss.read(4),16)
ddo.publicKeys.push(ss.read(pkLen))
const pkTotalLen = parseInt(ss.read(4),16)
if(pkTotalLen > 0) {
const pkNum = parseInt(ss.read(4), 16)
for (let i = 0; i < pkNum; i++) {
//length of public key - 4 bytes
let pkLen = parseInt(ss.read(4), 16)
let pubKey = new PublicKey()
const rawPk = ss.read(pkLen)
const type = parseInt(rawPk.substr(0, 2), 16)
const curve = parseInt(rawPk.substr(2, 2), 16)
const pk = rawPk.substr(4)
pubKey.algorithm = type
pubKey.curve = curve
pubKey.pk = pk
ddo.publicKeys.push(pubKey)
}
}


//attribute number - 4bytes
const attrTotalLen = parseInt(ss.read(4),16)
const attrNum = ss.readNextLen()
for(let i=0; i<attrNum;i++) {
let attrLen = parseInt(ss.read(4),16)
let attr = new DDOAttribute()
const pathLen = parseInt(ss.read(4), 16)
attr.path = hexstr2str(ss.read(pathLen))
attr.path = ss.read(pathLen)
if(attrTotalLen > 0) {
const attrNum = parseInt(ss.read(4), 16)
for (let i = 0; i < attrNum; i++) {
const totalLen = parseInt(ss.read(4), 16)

let attr = new DDOAttribute()
const pathLen = parseInt(ss.read(4), 16)
attr.path = hexstr2str(ss.read(pathLen))

const type_value_len = parseInt(ss.read(4), 16)
const typeLen = parseInt(ss.read(1), 16)
attr.type = hexstr2str(ss.read(typeLen))
const type_value_len = parseInt(ss.read(4), 16)
const typeLen = parseInt(ss.read(1), 16)
attr.type = hexstr2str(ss.read(typeLen))

const valueLen = type_value_len - typeLen - 1
attr.value = hexstr2str(ss.read(valueLen))
ddo.attributes.push(attr)
const valueLen = type_value_len - typeLen - 1
attr.value = hexstr2str(ss.read(valueLen))
ddo.attributes.push(attr)
}
}

//recovery
const recoveryTotalLen = parseInt(ss.read(4), 16)
if(recoveryTotalLen > 0 ) {
const recLen = parseInt(ss.read(4), 16)
const recovery = hexstr2str(ss.read(recLen))
ddo.recovery = recovery
}

return ddo
}
}
Loading

0 comments on commit 6921dcf

Please sign in to comment.