92 |
Create New API Key
93 |
94 |
113 |
114 | \n";
116 | }
117 |
118 | $read = isset($_POST['read']) ? 1 : 0;
119 | $trade = isset($_POST['trade']) ? 1 : 0;
120 | $withdraw = isset($_POST['withdraw']) ? 1 : 0;
121 | $deposit = isset($_POST['deposit']) ? 1 : 0;
122 |
123 | if (isset($_POST['add_key'])) {
124 | $name = post('name');
125 | $api_key = random_string(8,5);
126 | $secret = random_string(8,8);
127 |
128 | // don't generate keys too quickly
129 | usleep(rand(1e6, 2e6));
130 |
131 | $result = mysql_query("INSERT INTO api_keys (uid, name, api_key, secret, can_read, can_trade, can_withdraw, can_deposit)
132 | VALUES ('$is_logged_in', '$name', '$api_key', '$secret', '$read', '$trade', '$withdraw', '$deposit')");
133 | if (!$result)
134 | throw new Error("Error creating key", "Do you already have an API key with that name?");
135 | } else if (isset($_POST['update_permissions'])) {
136 | $name = post('name');
137 | $query = "
138 | UPDATE
139 | api_keys
140 | SET
141 | can_read = $read, can_trade = $trade, can_withdraw = $withdraw, can_deposit = $deposit
142 | WHERE
143 | uid = '$is_logged_in'
144 | AND
145 | name = '$name'
146 | ";
147 | do_query($query);
148 | } else if (isset($_POST['delete_key'])) {
149 | $name = post('name');
150 | $query = "DELETE FROM api_keys WHERE uid = '$is_logged_in' AND name = '$name'";
151 | do_query($query);
152 | }
153 |
154 | show_api_keys();
155 |
156 | ?>
157 |
--------------------------------------------------------------------------------
/backups/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/bank.php:
--------------------------------------------------------------------------------
1 | \n";
13 | echo "
Accounts
\n";
14 | $result = $xero->Accounts();
15 | if ($result['Status'] == 'OK') {
16 | echo "
list of accounts:
\n";
17 | foreach ($result['Accounts']['Account'] as $account) {
18 | echo "- ", $account['AccountID'], " : ", $account['Name'], "
\n";
19 | }
20 | echo "
\n";
21 | }
22 | echo "
\n";
23 | }
24 |
25 | function show_statement($xero, $account, $from = '', $to = '')
26 | {
27 | $result = $xero->BankStatement("?bankaccountid=$account$from$to");
28 | if ($result['Status'] == 'OK') {
29 | echo "\n";
30 | echo "
" . _("Statement") . "
\n";
31 |
32 | $report = $result['Reports']['Report'];
33 | echo "
Titles: ", implode($report['ReportTitles']['ReportTitle'], ' - '), "
\n";
34 | echo "
ReportDate: ", $report['ReportDate'], "
\n";
35 | $data = $report['Rows']['Row'];
36 |
37 | echo "
\n";
38 | // echo $data[0]['RowType'], "\n";
39 | echo "";
40 | foreach ($data[0]['Cells']['Cell'] as $cell)
41 | echo "", $cell['Value'], " | ";
42 | echo "";
43 | // echo $data[1]['RowType'], "\n";
44 | foreach ($data[1]['Rows']['Row'] as $row) {
45 | echo "";
46 | foreach ($row['Cells']['Cell'] as $cell) {
47 | if (isset($cell['Value'])) {
48 | $value = $cell['Value'];
49 | $value = str_replace('T00:00:00', '', $value);
50 | } else
51 | $value = '';
52 | echo "$value | ";
53 | }
54 | echo "
";
55 | echo "\n";
56 | }
57 | echo "
\n";
58 | }
59 | }
60 |
61 | function show_withdrawals()
62 | {
63 | echo "\n";
64 | echo "
" . _("Withdraw requests") . "
\n";
65 | $result = do_query("
66 | SELECT requests.reqid as reqid, uid, amount, " . sql_format_date("timest") . " as timest, name, bank, acc_num, sort_code
67 | FROM requests
68 | JOIN uk_requests
69 | ON uk_requests.reqid = requests.reqid
70 | WHERE req_type = 'WITHDR'
71 | AND curr_type = '" . CURRENCY . "'
72 | AND status = 'VERIFY'");
73 | $first = true;
74 | while ($row = mysql_fetch_assoc($result)) {
75 | if ($first) {
76 | $first = false;
77 |
78 | echo "
\n";
79 | echo "";
80 | // echo "User | ";
81 | echo "" . CURRENCY . " | ";
82 | echo "Time | ";
83 | echo "Name | ";
84 | echo "Bank | ";
85 | echo "Account# | ";
86 | echo "BSB | ";
87 | echo "
\n";
88 | }
89 | $reqid = $row['reqid'];
90 | // $uid = $row['uid'];
91 | $amount = internal_to_numstr($row['amount']);
92 | $timest = $row['timest'];
93 | $name = $row['name'];
94 | $bank = $row['bank'];
95 | $acc_num = $row['acc_num'];
96 | $sort_code = $row['sort_code'];
97 | echo "";
98 | echo active_table_row("me", "?page=view_request&reqid=$reqid&show_finish");
99 | // echo "$uid | ";
100 | echo "$amount | ";
101 | echo "$timest | ";
102 | echo "$name | ";
103 | echo "$bank | ";
104 | echo "$acc_num | ";
105 | echo "$sort_code | ";
106 | echo "
\n";
107 | }
108 |
109 | if ($first)
110 | echo "No pending withdrawals.
\n";
111 | else
112 | echo "
\n";
113 |
114 | echo "
\n";
115 | }
116 |
117 | $from = "&fromDate=1 Jan 2011";
118 | // $to = "&toDate=31 Dec 2011";
119 |
120 | // $xero = new Xero(XERO_KEY, XERO_SECRET, ABSPATH . "/bank/publickey.cer", ABSPATH . "/bank/privatekey.pem", 'json');
121 | // show_statement($xero, ACCOUNT, $from);
122 | // list_accounts($xero);
123 | show_withdrawals();
124 |
125 | ?>
126 |
--------------------------------------------------------------------------------
/bank/README.txt:
--------------------------------------------------------------------------------
1 | The basic command line steps to generate a private and public key using OpenSSL are as follows:
2 |
3 | # Step 1 – generates your private key
4 | openssl genrsa -out privatekey.pem 1024
5 |
6 | # Step 2 – generates your public key which you use when registering your private application
7 | openssl req -newkey rsa:1024 -x509 -key privatekey.pem -out publickey.cer -days 365
8 |
9 | # Step 3 – exports your public and private key to a pfx file which can be used to sign your OAuth messages.
10 | openssl pkcs12 -export -out public_privatekey.pfx -inkey privatekey.pem -in publickey.cer
11 |
12 | is step 3 needed?
13 |
--------------------------------------------------------------------------------
/bank/bank_config.php:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/bank/privatekey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
11 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
12 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
13 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
14 | XXXXXXXXXXXXXXXXXXXX+XXX+XXXXXXXXXXXXXXXXXX=
15 | -----END RSA PRIVATE KEY-----
16 |
--------------------------------------------------------------------------------
/bank/publickey.cer:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
11 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
12 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
13 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
14 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
15 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
16 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
17 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
18 | XXXXXXXXXXXXXXX=
19 | -----END CERTIFICATE-----
20 |
--------------------------------------------------------------------------------
/bin/every-hour:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | backup_wallet() {
4 | cd ~/.bitcoin
5 | ~/bin/bitcoind backupwallet ~/.bitcoin/wallet.dat.backupwallet
6 | rm -f wallet.dat.gpg
7 | gpg -c --no-tty --no-use-agent --passphrase-file pp wallet.dat.backupwallet
8 | rm -f wallet.dat.backupwallet
9 | mv wallet.dat.backupwallet.gpg wallet.dat.gpg
10 | }
11 |
12 | check_bitcoind() {
13 | date="$(date)"
14 | echo -n "$date : " >> ~/logs/bitcoind-ps.txt
15 | ps -fuworldbit | grep coin | grep daemon | grep -v grep >> ~/logs/bitcoind-ps.txt
16 | }
17 |
18 | check_bitcoind
19 | backup_wallet
20 |
--------------------------------------------------------------------------------
/bin/every-minute:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # bluehost has this going on to make sure user logins use fakefs mounts:
4 | #
5 | # $ ls -l /bin/bash* /bin/sh
6 | # lrwxrwxrwx 1 root root 14 Sep 14 02:13 /bin/bash -> /bin/fakeshell
7 | # -rwxr-xr-x 5 root root 801528 Jul 21 19:20 /bin/bash.orig
8 | # lrwxrwxrwx 2 root root 9 Sep 14 02:13 /bin/sh -> bash.orig
9 | #
10 | # changing the #! line to use /bin/bash.orig (hopefully!) allows bitcoind to survive the nightly fakefs rebuild
11 |
12 | # alternatively, we could use /bin/sh and turn POSIX mode back off, to get proper bash compatibility:
13 | #
14 | # #!/bin/sh
15 | # set +o posix
16 |
17 | . ~/db.intersango.sh
18 | ROOT=~
19 |
20 | BIN=$ROOT/bin
21 | INTERSANGO=$ROOT/intersango
22 | CRON=$INTERSANGO/cron
23 | LOGDIR=$INTERSANGO/logs
24 | LOGFILE=$LOGDIR/every-minute.txt
25 | BACKUPDIR=$INTERSANGO/backups
26 | BACKUP=$BACKUPDIR/db.txt
27 | LOCKDIR=$INTERSANGO/locks
28 | LOCKFILE=$LOCKDIR/every-minute.txt
29 | MAX_LOCK_AGE=10 # maximum amount of time a lock is allowed to survive, in minutes
30 |
31 | mkdir -p $LOCKDIR
32 |
33 | check_bitcoind() {
34 | printf "$(date) : $$ checking bitcoind\n"
35 | if ! pgrep -U "$USER" bitcoind > /dev/null
36 | then
37 | printf "$(date) : starting bitcoind\n" >> $LOGDIR/bitcoind.txt
38 | # md5sum ~/.bitcoin/blk* > /dev/null # get block data into disk cache for quicker start
39 | $BIN/bitcoind -daemon -keypool=1234
40 | mount > ~/cron/mount-after-starting-bitcoind.txt
41 | # $BIN/bitcoind -daemon -testnet
42 | fi
43 | }
44 |
45 | sync_to_bitcoin() {
46 | printf "$(date) : $$ syncing with bitcoin\n"
47 | (
48 | cd $CRON;
49 | php ./sync_to_bitcoin.php > /dev/null
50 | )
51 | }
52 |
53 | verify_deposits() {
54 | printf "$(date) : $$ verifying deposits\n"
55 | (
56 | cd $CRON;
57 | php ./verify_deposits.php > /dev/null
58 | )
59 | }
60 |
61 | verify_withdrawals_bitcoin() {
62 | printf "$(date) : $$ verifying bitcoin withdrawals\n"
63 | (
64 | cd $CRON;
65 | php ./verify_withdrawals_bitcoin.php > /dev/null
66 | )
67 | }
68 |
69 | process_orders() {
70 | printf "$(date) : $$ processing orders\n"
71 | mkdir -p $LOGDIR/process_orders
72 | (
73 | cd $CRON
74 | php ./process_orders.php > $LOGDIR/process_orders/$(date +%y.%m.%d-%H.%M.%S) 2>&1
75 | )
76 |
77 | # delete small logfiles
78 | find $LOGDIR/process_orders '(' -size 484c -o -size 118c ')' -delete
79 | }
80 |
81 | log_process_sizes() {
82 | echo; date; echo
83 | ps -o '%p %z %c' -u"$USER" | LC_COLLATE=C sort -k 3 | awk '{tot += $2; printf("%5s %6s %8s %s\n", $1, $2, tot ? tot/1024 : "SUM", $3); }'
84 | }
85 |
86 | backup_database() {
87 | printf "$(date) : $$ backing up database '$1'\n"
88 | mysqldump --extended-insert=false -u"$MYSQL_INTERSANGO_USER" "$MYSQL_INTERSANGO_DBNAME" -p"$MYSQL_INTERSANGO_PW" | sed -e 's/AUTO_INCREMENT=[0-9]* //' -e 's/\(INSERT INTO `api_keys`.*,\)[0-9]*\();\)/\10\2/' | grep -v '^-- Dump completed on' > $BACKUP.tmp
89 | mv $BACKUP.tmp $BACKUP
90 | cd $BACKUPDIR
91 | if [[ $(git diff $BACKUP | wc -l) != 0 ]]
92 | then
93 | git commit --quiet --message="$1" $BACKUP
94 | fi
95 | }
96 |
97 | get_lock() {
98 | if [[ -f $LOCKFILE ]]
99 | then
100 | # if the lock is old, probably a previous incarnation of this script crashed so delete the lock
101 | find $LOCKFILE -mmin +$MAX_LOCK_AGE -delete
102 |
103 | if [[ -f $LOCKFILE ]]
104 | then
105 | printf "$(date) : $$ locked : $(ls -l $LOCKFILE)\n\n"
106 | exit
107 | fi
108 |
109 | printf "$(date) : $$ force unlocked\n"
110 | fi
111 |
112 | touch $LOCKFILE
113 | printf "$(date) : $$ got lock\n"
114 | }
115 |
116 | release_lock() {
117 | rm -f $LOCKFILE
118 | printf "$(date) : $$ released lock\n"
119 | }
120 |
121 | run_jobs() {
122 | printf "$(date) : $$ start\n"
123 | get_lock
124 |
125 | check_bitcoind # check whether bitcoind is running, and if not, run it
126 | backup_database "before cron"
127 | sync_to_bitcoin; backup_database "synced bitcoin" # check for and process new btc deposits
128 | verify_deposits; backup_database "verified deposits" # check for and process new deposits
129 | verify_withdrawals_bitcoin; backup_database "verified bitcoin withdrawals" # check for and process new bitcoin withdrawals
130 | process_orders; backup_database "processed orders" # check for and process new orders
131 | log_process_sizes >> $LOGDIR/ps.txt
132 |
133 | release_lock
134 | printf "$(date) : $$ end\n\n"
135 | }
136 |
137 | main() {
138 | run_jobs >> $LOGFILE
139 | }
140 |
141 | main
142 |
--------------------------------------------------------------------------------
/cert/facacbc6.0:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
3 | yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
4 | ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
5 | U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
6 | ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
7 | aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
8 | MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
9 | ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
10 | biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
11 | U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
12 | aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
13 | nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
14 | t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
15 | SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
16 | BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
17 | rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
18 | NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
19 | BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
20 | BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
21 | aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
22 | MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
23 | p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
24 | 5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
25 | WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
26 | 4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
27 | hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
28 | -----END CERTIFICATE-----
29 |
--------------------------------------------------------------------------------
/commission.php:
--------------------------------------------------------------------------------
1 | ", internal_to_numstr($amount, $precision), "";
7 | }
8 |
9 | ?>
10 |
11 |
12 | \n";
15 |
16 | echo "
\n";
17 | echo "
" . _("Commission") . "
\n";
18 |
19 | $query = "
20 | SELECT txid,
21 | a_orderid, a_amount, a_commission,
22 | b_orderid, b_amount, b_commission, " .
23 | sql_format_date("t.timest") . " as timest,
24 | a.uid as a_uid, b.uid as b_uid
25 | FROM transactions AS t
26 | JOIN
27 | orderbook AS a
28 | ON
29 | a.orderid = a_orderid
30 | JOIN
31 | orderbook AS b
32 | ON
33 | b.orderid = b_orderid
34 | WHERE a_commission != 0
35 | OR b_commission != 0
36 | ORDER BY txid;
37 | ";
38 | $result = do_query($query);
39 | $first = true;
40 | $commission_fiat_total = $commission_btc_total = '0';
41 | $amount_fiat_total = $amount_btc_total = '0';
42 | $cells = array();
43 | while ($row = mysql_fetch_assoc($result)) {
44 | if ($first) {
45 | $first = false;
46 | echo "
\n";
47 | echo "";
48 | echo " | ";
49 | echo "" . CURRENCY . " | ";
50 | echo "BTC | ";
51 | echo "
";
52 | echo "";
53 | echo "" . _("TID") . " | ";
54 | echo "" . _("Got") . " | ";
55 | echo "" . _("Fee") . " | ";
56 | echo "" . _("Got") . " | ";
57 | echo "" . _("Fee") . " | ";
58 | echo "" . _("Date") . " | ";
59 | echo "
";
60 | }
61 |
62 | $txid = $row['txid'];
63 | $a_orderid = $row['a_orderid'];
64 | $a_amount = $row['a_amount'];
65 | $a_commission = $row['a_commission'];
66 | $b_orderid = $row['b_orderid'];
67 | $b_amount = $row['b_amount'];
68 | $b_commission = $row['b_commission'];
69 | $timest = $row['timest'];
70 | $a_uid = $row['a_uid'];
71 | $b_uid = $row['b_uid'];
72 |
73 | $amount_fiat_total = gmp_add($amount_fiat_total, $a_amount);
74 | $amount_btc_total = gmp_add($amount_btc_total, $b_amount);
75 |
76 | $commission_fiat_total = gmp_add($commission_fiat_total, $a_commission);
77 | $commission_btc_total = gmp_add($commission_btc_total, $b_commission);
78 |
79 | if (isset($cells[$a_orderid]))
80 | array_push($cells[$a_orderid], "'".$txid."'");
81 | else
82 | $cells[$a_orderid] = array("'".$txid."'");
83 |
84 | if (isset($cells[$b_orderid]))
85 | array_push($cells[$b_orderid], "'".$txid."'");
86 | else
87 | $cells[$b_orderid] = array("'".$txid."'");
88 |
89 | echo "";
90 | echo "$txid | ";
91 | active_table_cell_link_for_commission($a_uid, $txid, $b_orderid, 'amount', $a_amount , FIAT_PRECISION);
92 | active_table_cell_link_for_commission($a_uid, $txid, $b_orderid, 'comm', $a_commission, FIAT_PRECISION);
93 | active_table_cell_link_for_commission($b_uid, $txid, $a_orderid, 'amount', $b_amount , BTC_PRECISION);
94 | active_table_cell_link_for_commission($b_uid, $txid, $a_orderid, 'comm', $b_commission, BTC_PRECISION);
95 | echo "$timest | ";
96 | echo "
\n";
97 | }
98 |
99 | if (!$first) {
100 | echo " \n";
101 | echo " | -------- | -------- | -------- | -------- | \n";
102 | echo "
\n";
103 | echo " \n";
104 | echo " | ";
105 | echo " ", internal_to_numstr($amount_fiat_total, FIAT_PRECISION), " | ";
106 | echo " ", internal_to_numstr($commission_fiat_total, FIAT_PRECISION), " | ";
107 | echo " ", internal_to_numstr($amount_btc_total, BTC_PRECISION), " | ";
108 | echo " ", internal_to_numstr($commission_btc_total, BTC_PRECISION), " | ";
109 | echo "
\n";
110 | echo "
\n";
111 | }
112 |
113 | $commissions = fetch_balances('1');
114 | printf("
" . _("In the commission purse, there is %s %s and %s %s.") . "\n",
115 | internal_to_numstr($commissions[CURRENCY], FIAT_PRECISION),
116 | CURRENCY,
117 | internal_to_numstr($commissions['BTC'], BTC_PRECISION),
118 | "BTC");
119 | echo _("Hopefully that matches with the totals shown above.") . "
\n";
120 | ?>
121 |
151 |
152 |
--------------------------------------------------------------------------------
/cron/bankd/check_bank_changed_format.py:
--------------------------------------------------------------------------------
1 | import MySQLdb
2 |
3 | db = MySQLdb.connect("localhost", "root", "", "intersango")
4 | c = db.cursor()
5 | c.execute("""
6 | SELECT *
7 | FROM bank_statement
8 | WHERE bank_name='LloydsTSB'
9 | """)
10 | count = 0
11 | fin_bids = []
12 | for b1 in c.fetchall():
13 | entry1 = b1[2].split(',')
14 | bid = b1[0]
15 | fin_bids.append(bid)
16 | balance = entry1[-1]
17 | c.execute("""
18 | SELECT *
19 | FROM bank_statement
20 | WHERE
21 | entry LIKE '%%%s'
22 | AND bank_name='LloydsTSB'
23 | AND bid!='%i'
24 | AND status!='PAYOUT'
25 | """%(balance, bid))
26 | for b2 in c.fetchall():
27 | if b2[0] in fin_bids or b2[3] is None or b1[3] is None:
28 | continue
29 | count += 1
30 | print 'Found -------------------'
31 | print b1
32 | print '####'
33 | print b2
34 | reqid1 = b1[3]
35 | reqid2 = b2[3]
36 | c.execute("""
37 | SELECT *
38 | FROM requests
39 | WHERE reqid IN (%i, %i)
40 | """%(reqid1, reqid2))
41 | reqs = c.fetchall()
42 | print
43 | uid = None
44 | for r in reqs:
45 | if uid is None:
46 | uid = r[2]
47 | elif uid != r[2]:
48 | print 'IGNOREEEEE******************************'
49 | print r
50 | c.execute("""
51 | SELECT *
52 | FROM purses
53 | WHERE
54 | uid=%i
55 | AND type='AUD'
56 | """%uid)
57 | print c.fetchall()
58 | print '-------------------------'
59 |
60 | print 'Total:', count
61 |
--------------------------------------------------------------------------------
/cron/bankd/finalize_withdrawals.php:
--------------------------------------------------------------------------------
1 | $line) {
19 | $line = mysql_real_escape_string($line);
20 | $query = "
21 | INSERT IGNORE INTO
22 | bank_statement (bank_name, entry)
23 | VALUES (
24 | '$bank_name',
25 | '$line'
26 | )
27 | ";
28 | do_query($query);
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/cron/bankd/import_csv_hsbc.py:
--------------------------------------------------------------------------------
1 | import MySQLdb
2 | import hashlib
3 | import sys
4 |
5 | def database_handle():
6 | return MySQLdb.connect('localhost', 'root', '', 'intersango')
7 |
8 | def show_help():
9 | print 'python import_csv_hsbc.py [FILENAME]'
10 |
11 | def import_lines(lines):
12 | handle = database_handle()
13 | cursor = handle.cursor()
14 | print
15 | for line in lines:
16 | print 'Importing:', line
17 | cursor.execute("""
18 | INSERT INTO
19 | bank_statement (bank_name, entry)
20 | VALUES (
21 | 'HSBC',
22 | '%s'
23 | )
24 | """%line)
25 |
26 | def read_file(filename):
27 | handle = open(filename)
28 | text = handle.read()
29 | lines = text.split('\n')
30 | # HSBC orders files backwards from newest to oldest by default
31 | # re-order correctly the file
32 | lines.reverse()
33 | # remove empty element
34 | if lines[0] == '':
35 | lines = lines[1:]
36 | return lines
37 |
38 | def read_database(num_lines):
39 | handle = database_handle()
40 | cursor = handle.cursor()
41 | # select last num_lines entries from bank_statement
42 | # we do that using a sub-query that orders desc, selects first X lines
43 | # then re-orders it asc
44 | cursor.execute("""
45 | SELECT entry
46 | FROM (
47 | SELECT
48 | bid, entry
49 | FROM
50 | bank_statement
51 | WHERE
52 | bank_name='HSBC'
53 | ORDER BY
54 | bid DESC
55 | LIMIT
56 | %i
57 | ) AS b
58 | ORDER BY bid ASC
59 | """%num_lines)
60 | return [c for c, in cursor.fetchall()]
61 |
62 | def run_parser():
63 | if len(sys.argv) != 2:
64 | show_help()
65 | return -1
66 | csv_lines = read_file(sys.argv[1])
67 | db_lines = read_database(len(csv_lines))
68 | print db_lines
69 | print
70 | print csv_lines
71 |
72 | hash_pair = lambda line: (hashlib.sha512(line).digest(), line)
73 | make_hash_pairs = lambda lines: [hash_pair(l) for l in lines]
74 | csv_pairs = make_hash_pairs(csv_lines)
75 | db_pairs = make_hash_pairs(db_lines)
76 |
77 | while len(db_pairs) > 0 and csv_pairs[0][0] != db_pairs[0][0]:
78 | print 'Dropping:', db_pairs.pop(0)[1]
79 |
80 | if len(db_pairs) == 0:
81 | # No matching lines
82 | import_lines(csv_lines)
83 | return 0
84 |
85 | while len(db_pairs) > 0:
86 | # Make sure that at least first hashe from both sets of lines match
87 | assert(csv_pairs[0][0] == db_pairs[0][0])
88 | print 'Deleting:', csv_pairs.pop(0)[1]
89 | db_pairs.pop(0)
90 |
91 | remaining_lines = [line[1] for line in csv_pairs]
92 | print 'Remaining lines:', remaining_lines
93 | import_lines(remaining_lines)
94 |
95 | if __name__ == '__main__':
96 | sys.exit(run_parser())
97 |
98 |
--------------------------------------------------------------------------------
/cron/bankd/mark_withdrawals.php:
--------------------------------------------------------------------------------
1 | = 1:
21 | good_reference = False
22 | for match in matches:
23 | deposit_reference = match.strip('., \t\r\n"')
24 | amount = int(decimal.Decimal(line[6]) * ( 10 ** 8))
25 | c.execute('SELECT uid FROM users WHERE deposref=%s',(deposit_reference,))
26 | result = c.fetchone()
27 | if result:
28 | uid = result[0]
29 |
30 | c.execute("""
31 | UPDATE
32 | bank_statement
33 | SET
34 | status='PROC'
35 | WHERE
36 | bid=%s""",(bid,))
37 |
38 | c.execute("""
39 | INSERT INTO requests (
40 | req_type,
41 | curr_type,
42 | uid,
43 | amount
44 | )
45 | VALUES
46 | (
47 | 'DEPOS',
48 | 'AUD',
49 | %s,
50 | %s
51 | )""",(uid,amount))
52 |
53 | reqid = c.lastrowid
54 |
55 | c.execute("""
56 | UPDATE
57 | bank_statement
58 | SET
59 | reqid=%s,
60 | status='FINAL'
61 | WHERE
62 | bid=%s""",(reqid,bid))
63 |
64 | print("DEPOS",bid,uid,amount,reqid,entry)
65 |
66 | good_reference = True
67 | break
68 |
69 | if not good_reference:
70 | print("BADREF",entry)
71 | c.execute("UPDATE bank_statement SET status='BADREF' WHERE bid=%s",(bid,))
72 | except StopIteration:
73 | pass
74 |
75 |
--------------------------------------------------------------------------------
/cron/bankd/reject_withdrawal.php:
--------------------------------------------------------------------------------
1 | $balance) {
8 | if ($balance) {
9 | try {
10 | get_openid_for_user($account); // check they have an account
11 | } catch (Exception $e) { continue; }
12 |
13 | get_user_lock($account);
14 | addlog(LOG_CRONJOB, sprintf("add %s BTC for user %s", internal_to_numstr($balance), $account));
15 | sync_to_bitcoin((string)$account);
16 | release_lock($account);
17 | }
18 | }
19 |
20 | ?>
21 |
--------------------------------------------------------------------------------
/cron/verify_deposits.php:
--------------------------------------------------------------------------------
1 | getTitle()}\"\n {$e->getMessage()}\n";
68 | }
69 | catch (Problem $e) {
70 | echo "\nProblem: \"{$e->getTitle()}\"\n {$e->getMessage()}\n";
71 | }
72 | catch (Exception $e) {
73 | echo "\nException: \"{$e->getTitle()}\"\n {$e->getMessage()}\n";
74 | }
75 | ?>
76 |
--------------------------------------------------------------------------------
/cron/verify_withdrawals_bitcoin.php:
--------------------------------------------------------------------------------
1 | getTitle() == 'Lock Error')
56 | echo "can't get lock for $uid\n";
57 | else
58 | throw $e;
59 | }
60 | }
61 |
62 | $query = "
63 | SELECT
64 | requests.reqid AS reqid,
65 | users.uid AS uid,
66 | amount,
67 | addy
68 | FROM requests
69 | JOIN bitcoin_requests
70 | ON requests.reqid=bitcoin_requests.reqid
71 | JOIN users
72 | ON users.uid=requests.uid
73 | WHERE
74 | req_type='WITHDR'
75 | AND amount > 1000000
76 | AND status='VERIFY'
77 | AND curr_type='BTC'
78 | ";
79 |
80 | if (REQUIRE_IDENTIFICATION)
81 | $query .= "AND (users.uid < " . LOWEST_UNTRUSTED_USERID . " OR verified)";
82 |
83 | $result = do_query($query);
84 | while ($row = mysql_fetch_assoc($result)) {
85 | $reqid = $row['reqid'];
86 | $uid = $row['uid'];
87 | $amount = $row['amount'];
88 | $addy = $row['addy'];
89 | $we_have = bitcoin_get_balance("*", CONFIRMATIONS_FOR_DEPOSIT);
90 |
91 | // add on anything we've recently sent from offline storage but which isn't fully confirmed yet
92 | $main_unconfirmed = gmp_sub(bitcoin_get_balance("", 1), bitcoin_get_balance("", CONFIRMATIONS_FOR_DEPOSIT));
93 | $we_have = gmp_add($we_have, $main_unconfirmed);
94 |
95 | addlog(LOG_CRONJOB, "Attempting to withdraw " . internal_to_numstr($amount) .
96 | " of " . internal_to_numstr($we_have) . " BTC for user $uid (reqid $reqid)");
97 |
98 | if (gmp_cmp($we_have, $amount) >= 0) {
99 | update_req($reqid, "PROCES");
100 |
101 | // use 'sendtoaddress' rather than 'sendfrom' because it can 'go overdrawn'
102 | // so long as there are funds in other accounts (pending deposits) to cover it
103 | bitcoin_send_to_address($addy, $amount);
104 | update_req($reqid, "FINAL");
105 |
106 | $we_have = bitcoin_get_balance("*", 0);
107 | addlog(LOG_CRONJOB, "We have " . internal_to_numstr($we_have) . " BTC in total");
108 | if (gmp_cmp($we_have, numstr_to_internal(WARN_LOW_WALLET_THRESHOLD)) < 0)
109 | email_tech(_("Exchange Wallet Balance is Low"),
110 | sprintf(_("The exchange wallet only has %s BTC available."),
111 | internal_to_numstr($we_have, BTC_PRECISION)));
112 | } else {
113 | $message = sprintf(_("We only have %s BTC so can't withdraw %s BTC"),
114 | internal_to_numstr($we_have, BTC_PRECISION),
115 | internal_to_numstr($amount, BTC_PRECISION));
116 | addlog(LOG_CRONJOB, $message);
117 | // email_tech(_("Exchange Wallet Balance is Too Low"), $message);
118 | }
119 | }
120 | }
121 | catch (Error $e) {
122 | report_exception($e, SEVERITY::ERROR);
123 | // Same as below, but flag + log this for review,
124 | echo "\nError: \"{$e->getTitle()}\"\n {$e->getMessage()}\n";
125 | }
126 | catch (Problem $e) {
127 | echo "\nProblem: \"{$e->getTitle()}\"\n {$e->getMessage()}\n";
128 | }
129 | catch (Exception $e) {
130 | echo "\nException: \"{$e->getTitle()}\"\n {$e->getMessage()}\n";
131 | }
132 | ?>
133 |
--------------------------------------------------------------------------------
/crontab.txt:
--------------------------------------------------------------------------------
1 | * * * * * intersango/bin/every-minute
2 | 0 * * * * intersango/bin/every-hour
3 |
--------------------------------------------------------------------------------
/db.php:
--------------------------------------------------------------------------------
1 | \n";
13 | $result = mysql_query($query);
14 | if (!$result)
15 | throw new Error(_("MySQL Error"), mysql_error());
16 | return $result;
17 | }
18 | function has_results($result)
19 | {
20 | if (mysql_num_rows($result) > 0)
21 | return true;
22 | else
23 | return false;
24 | }
25 | function get_row($result)
26 | {
27 | $row = mysql_fetch_array($result, MYSQL_ASSOC);
28 | if (!$row)
29 | throw new Error('Ooops!', "Seems there's a missing value here.");
30 | return $row;
31 | }
32 |
33 | function numstr_to_internal($numstr)
34 | {
35 | return bcmul($numstr, pow(10, 8), 0);
36 | }
37 |
38 | function internal_to_numstr($num, $precision=-1, $round = true)
39 | {
40 | if ($precision == -1) {
41 | $precision = 8;
42 | $tidy = true;
43 | } else
44 | $tidy = false;
45 |
46 | if (!is_string($num) && !is_resource($num))
47 | throw new Error('Coding error!', "internal_to_numstr argument has type '" . gettype($num) . "'");
48 | $repr = gmp_strval($num);
49 | if ($round)
50 | if ($repr > 0)
51 | $repr = bcadd($repr, pow(10, (8 - $precision)) / 2);
52 | else
53 | $repr = bcsub($repr, pow(10, (8 - $precision)) / 2);
54 | $repr = bcdiv($repr, pow(10, 8), $precision);
55 |
56 | // now tidy output...
57 | if ($tidy)
58 | return clean_sql_numstr($repr);
59 | return sprintf("%.{$precision}f", $repr);
60 | }
61 |
62 | function clean_sql_numstr($numstr)
63 | {
64 | if (strpos($numstr, '.') !== false) {
65 | $numstr = rtrim($numstr, '0');
66 | $numstr = rtrim($numstr, '.');
67 | }
68 | return $numstr;
69 | }
70 |
71 | do_query("set time_zone = '".TIMEZONE."'");
72 |
73 | ?>
74 |
--------------------------------------------------------------------------------
/demo.php:
--------------------------------------------------------------------------------
1 | info());
12 | var_dump($wbx->get_deposit_address());
13 | var_dump($wbx->cancel_order(12345));
14 |
15 | ?>
16 |
--------------------------------------------------------------------------------
/deposit.php:
--------------------------------------------------------------------------------
1 |
25 |
26 |
27 | |
28 | |
29 |
30 |
31 | |
32 | |
33 |
34 |
35 | |
36 | |
37 |
38 |
39 | |
40 | |
41 |
42 |
43 | |
44 | |
45 |
46 |
47 |
52 |
53 |
59 |
60 | \n";
65 | echo "
" . _("Deposit Voucher") . "
\n";
66 | $code = post('code', '-');
67 | try {
68 | get_lock("redeem_voucher", 2);
69 | list ($curr_type, $amount) = redeem_voucher($code);
70 | echo ("
" .
71 | sprintf(_("%s has been credited to your account."),
72 | internal_to_numstr($amount) . " $curr_type") .
73 | "
\n");
74 | echo "
" . _("got any more?") . "
\n";
75 | show_deposit_voucher_form($code);
76 | } catch (Exception $e) {
77 | $message = $e->getMessage();
78 | echo "
" . _("error") . ": $message
\n";
79 | echo "
" . _("try again?") . "
\n";
80 | show_deposit_voucher_form($code);
81 | }
82 | release_lock("redeem_voucher");
83 | echo "
\n";
84 | } else {
85 | try {
86 | $addy = bitcoin_get_account_address((string)$is_logged_in);
87 | } catch (Exception $e) {
88 | if ($e->getMessage() != 'Unable to connect.')
89 | throw $e;
90 | $addy = '';
91 | }
92 |
93 | $query = "
94 | SELECT deposref
95 | FROM users
96 | WHERE uid='$is_logged_in';
97 | ";
98 | $result = do_query($query);
99 | $row = get_row($result);
100 | $deposref = $row['deposref'];
101 | $formatted_deposref = format_deposref($deposref);
102 |
103 | if (ENABLE_LOCAL_VOUCHERS) { ?>
104 |
105 |
106 |
110 |
111 |
114 |
115 |
", CURRENCY, "", CURRENCY); ?>
118 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
How should the user deposit PP?
130 |
Is there an API? Or should we just have the user fill in a form with:
- forum username
- forum password
- amount to transfer
131 |
132 | %s so we know which account to credit."), $formatted_deposref);
135 | $ref = $deposref;
136 | }
137 | ?>
138 |
139 |
140 |
141 |
142 |
BTC
143 | " . sprintf(_("You can deposit to %s"), "
$addy") . "\n";
146 | echo "
" . _("The above address is specific to your account. Each time you deposit, a new address will be generated for you.") . "
\n";
147 | echo "
" . sprintf(_("It takes %s confirmations before funds are added to your account."), CONFIRMATIONS_FOR_DEPOSIT) . "
\n";
148 | if (!$is_verified)
149 | echo "
Note that you will be able to deposit BTC and trade them back and forth for AUD, but until you identify yourself, you will be unable to make any withdrawls.
\n";
150 | } else
151 | echo "
" . _("We are currently experiencing trouble connecting to the Bitcoin network. Please try again in a few minutes.") . "
\n";
152 | echo "
\n";
153 | }
154 |
--------------------------------------------------------------------------------
/doc/process_order:
--------------------------------------------------------------------------------
1 | ==============================
2 | How does order matching work?
3 | ==============================
4 |
5 | When you place an order, it goes into the orderbook. Every new order is umarked
6 | at first. It just gets filed to be processed.
7 |
8 | Every minute, cron kicks in and starts processing the orders. Each matched order
9 | is marked with a flag indicating that it's been processed.
10 |
11 | For each order that is processed, we look to find other equivalent orders which
12 | are open, want the currency we own, have the currency we want and have a rate
13 | equivalent to or better than us. Looping through the matching orders with no
14 | ordering (we plan to fix that) we try to fulfill our order with the opposing
15 | order. Each loop creates a new transaction that indicates a trade occured
16 | between two users.
17 |
18 | We keep doing this until the entire order is fullfilled (order is closed) or we
19 | run out of matching orders; the remaining amount stays in the orderbook (order
20 | is open).
21 |
22 | The fulfilling part checks to see if our order has a smaller depth than the
23 | other one. If so, our order is completed at their exchange rate and closed. The
24 | matching finishes up.
25 |
26 | The other case is where we have a larger depth, and want to fulfill ourself
27 | partly using their order.
28 |
29 | ...
30 | Order 14: We are offering 10 AUD for 1 BC
31 | ...
32 | Order 18: They are offering 2.5 BC for 5 AUD
33 | ...
34 |
35 | We need to calculate how much of our order will be chipped off, while
36 | preserving their exchange rate.
37 |
38 | ...
39 | Order 14-1: We are offering 5 AUD for 0.5 BC
40 | Order 14-2: We are offering 5 AUD for 0.5 BC
41 | ...
42 |
43 | We fulfill our order and close their order.
44 |
45 | ...
46 | Order 14-2: We are offering 5 AUD for 0.5 BC
47 | ...
48 |
49 | A new transaction is created for record keeping purposes and the users funds are
50 | updated accordingly.
51 |
52 | A better algorithm would firstly order the matching equivalent orders by best
53 | price first so we move up the orderbook, rather than select random matches.
54 | Secondly an improvement perform linear programming to find the optimised rate
55 | for two given orders given the constraints- although that isn't too important.
56 |
57 | One minor addition would be to never accept orders where the want / offer
58 | doesn't produce a perfectly divisible amount so we don't get these random
59 | remainders that are credited to a random account once the order matching is
60 | completed.
61 |
62 | * See process_orders.php. pacman does the order fulfillment once the new amounts
63 | are computed.
64 |
65 |
--------------------------------------------------------------------------------
/docs.php:
--------------------------------------------------------------------------------
1 | \n";
19 | echo "" . sprintf(_("User %s hasn't uploaded anything."), $uid) . "
\n";
24 | echo "\n";
25 | return;
26 | }
27 |
28 | echo "\n";
39 | $dp = opendir($dir);
40 | $candidates = array();
41 | while ($file = readdir($dp)) {
42 | if ($file == '00-README.txt' || $file == '.' || $file == '..') continue;
43 | echo "