-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcustom-data.ts
73 lines (60 loc) · 1.83 KB
/
custom-data.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @module index
*/
import { signBytes, blake2b, base58Encode, publicKey, concat, TSeed } from '@waves/ts-lib-crypto'
import { schemas, serializePrimitives } from '@waves/marshall'
import { binary } from '@waves/marshall'
import { validate } from '../validators'
import { TPrivateKey } from '../types'
import {DataFiledType, DataTransactionEntry} from '@waves/ts-types'
import {DataTransactionDeleteRequest} from '@waves/ts-types/src/parts'
export interface ICustomDataV1 {
version: 1
/**
* base64 encoded UInt8Array
*/
binary: string // base64
publicKey?: string
}
export interface ICustomDataV2 {
version: 2
data: Exclude<DataTransactionEntry, DataTransactionDeleteRequest>[]
publicKey?: string
}
export type TCustomData = ICustomDataV1 | ICustomDataV2
export type TSignedData = TCustomData & {
/**
* base58 public key
*/
publicKey: string | undefined
/**
* base58 encoded blake2b(serialized data)
*/
hash: string
/**
* base58 encoded signature
*/
signature: string | undefined
}
/**
* Signs [[TCustomData]]
*/
export function customData(cData: TCustomData, seed?: TSeed | TPrivateKey): TSignedData {
validate.customData(cData)
let bytes = serializeCustomData(cData)
const hash = base58Encode(blake2b(bytes))
const pk = cData.publicKey ? cData.publicKey : seed && publicKey(seed)
const signature = seed && signBytes(seed, bytes)
return {...cData, hash, publicKey: pk, signature}
}
export function serializeCustomData(d: TCustomData){
if (d.version === 1) {
return concat([255, 255, 255, 1], serializePrimitives.BASE64_STRING(d.binary))
} else if (d.version === 2) {
const ser = binary.serializerFromSchema(schemas.txFields.data[1])
return concat([255, 255, 255, 2], ser(d.data))
} else {
//@ts-ignore
throw new Error(`Invalid CustomData version: ${d!.version}`)
}
}