1 | var fs = require('fs')
|
2 | , loadWallet = require('../utils/loadWallet')
|
3 | , crypto = require('crypto')
|
4 | , Progress = require('progress')
|
5 | , writeHeader = require('../utils/writeHeader')
|
6 | , printHeader = require('../utils/printHeader')
|
7 | , bs58 = require('bs58')
|
8 | , headersFromArgs = require('../utils/headersFromArgs')
|
9 | , isUtf8 = require('is-utf8')
|
10 | , createMessage = require('../lib/message').create
|
11 | , translateHeader = require('../utils/translateHeader')
|
12 |
|
13 | module.exports = function (inFile, outFile, options) {
|
14 | options.headers = headersFromArgs()
|
15 | options.headers['hash-algorithm'] = options.hash
|
16 | if (!options.armor) {
|
17 | if (!outFile) {
|
18 | outFile = inFile + '.salty-sig'
|
19 | }
|
20 | try {
|
21 | fs.statSync(outFile)
|
22 | if (!options.parent.force) {
|
23 | throw new Error('Refusing to overwrite ' + outFile + '. Use --force to ignore this.')
|
24 | }
|
25 | }
|
26 | catch (err) {
|
27 | if (err && err.code !== 'ENOENT') {
|
28 | throw err
|
29 | }
|
30 | }
|
31 | }
|
32 | loadWallet(options.parent.wallet, function (err, wallet) {
|
33 | if (err) throw err
|
34 | var inStat = fs.statSync(inFile)
|
35 | var inStream = fs.createReadStream(inFile)
|
36 | var chunks = []
|
37 | var header = {
|
38 | 'from-salty-id': wallet.pubkey.pubkey
|
39 | }
|
40 | if (options.armor) {
|
41 | options.headers['content-transfer-encoding'] = '8bit'
|
42 | inStream.on('data', function (chunk) {
|
43 | if (!isUtf8(chunk)) {
|
44 | header['content-transfer-encoding'] = 'base64'
|
45 | }
|
46 | chunks.push(chunk)
|
47 | })
|
48 | }
|
49 | else {
|
50 | var bar = new Progress(' hashing [:bar] :percent ETA: :etas', { total: inStat.size, width: 80 })
|
51 | inStream.on('data', function (chunk) {
|
52 | bar.tick(chunk.length)
|
53 | })
|
54 | }
|
55 | Object.keys(options.headers).forEach(function (k) {
|
56 | header[k] = options.headers[k]
|
57 | })
|
58 | var hashStream = crypto.createHash(header['hash-algorithm'])
|
59 | hashStream.once('data', function (hash) {
|
60 | if (!options.armor) {
|
61 | bar.terminate()
|
62 | }
|
63 | header['hash'] = hash.toString('hex')
|
64 | var headerStr = writeHeader(header)
|
65 |
|
66 | header['signature'] = bs58.encode(wallet.sign(Buffer(headerStr), true))
|
67 | var finalHeader = writeHeader(header)
|
68 | if (options.armor) {
|
69 | var buf = Buffer.concat(chunks)
|
70 | var out = createMessage(header, buf)
|
71 | header = options.translate ? translateHeader(header, wallet.recipients) : header
|
72 | printHeader(header)
|
73 | console.log(out)
|
74 | }
|
75 | else {
|
76 | fs.writeFileSync(outFile, finalHeader)
|
77 | printHeader(header)
|
78 | console.log('Wrote signature to', outFile)
|
79 | }
|
80 | })
|
81 | inStream.pipe(hashStream)
|
82 | inStream.resume()
|
83 | })
|
84 | } |
\ | No newline at end of file |