-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExamplePaymentChannelServer.java
153 lines (132 loc) · 6.51 KB
/
ExamplePaymentChannelServer.java
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoinj_test;
import com.google.bitcoin.core.*;
import com.google.bitcoin.kits.WalletAppKit;
import com.google.bitcoin.params.TestNet3Params;
import com.google.bitcoin.protocols.channels.*;
import com.google.bitcoin.utils.BriefLogFormatter;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.SocketAddress;
/**
* Simple server that listens on port 4242 for incoming payment channels.
*/
public class ExamplePaymentChannelServer implements PaymentChannelServerListener.HandlerFactory {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(ExamplePaymentChannelServer.class);
private StoredPaymentChannelServerStates storedStates;
private WalletAppKit appKit;
private Runtime r = Runtime.getRuntime();
private Process p;
private String clientMac;
public static void main(String[] args) throws Exception {
BriefLogFormatter.init();
new ExamplePaymentChannelServer().run();
}
public void run() throws Exception {
NetworkParameters params = TestNet3Params.get();
// Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we
// can customize it by adding the extension objects - we have to do this before the wallet file is loaded so
// the plugin that knows how to parse all the additional data is present during the load.
appKit = new WalletAppKit(params, new File("."), "payment_channel_example_server") {
@Override
protected void addWalletExtensions() {
// The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting
// the refund transaction if its lock time has expired. It also persists channels so we can resume them
// after a restart.
storedStates = new StoredPaymentChannelServerStates(wallet(), peerGroup());
wallet().addExtension(storedStates);
}
};
appKit.startAndWait();
System.out.println(appKit.wallet());
// We provide a peer group, a wallet, a timeout in seconds, the amount we require to start a channel and
// an implementation of HandlerFactory, which we just implement ourselves.
new PaymentChannelServerListener(appKit.peerGroup(), appKit.wallet(), 15, Utils.CENT, this).bindAndStart(4242);
}
@Override
public ServerConnectionEventHandler onNewConnection(final SocketAddress clientAddress) {
// Each connection needs a handler which is informed when that payment channel gets adjusted. Here we just log
// things. In a real app this object would be connected to some business logic.
return new ServerConnectionEventHandler() {
@Override
public void channelOpen(Sha256Hash channelId) {
log.info("Channel open for {}: {}.", clientAddress, channelId);
try {
p = r.exec("arp -a " + clientAddress.toString() + " | awk '{ print $4 }' ");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
clientMac = reader.readLine();
while (clientMac != null) {
clientMac = reader.readLine();
System.out.println(clientMac);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p = r.exec("sudo iptables -t mangle -I internet 1 -m mac --mac-source " + clientMac + " -j RETURN");
p.waitFor();
p = r.exec("sudo rmtrack " + clientAddress.toString());
p.waitFor();
} catch (IOException | InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Try to get the state object from the stored state set in our wallet
PaymentChannelServerState state = null;
try {
state = storedStates.getChannel(channelId).getOrCreateState(appKit.wallet(), appKit.peerGroup());
} catch (VerificationException e) {
// This indicates corrupted data, and since the channel was just opened, cannot happen
throw new RuntimeException(e);
}
log.info(" with a maximum value of {}, expiring at UNIX timestamp {}.",
// The channel's maximum value is the value of the multisig contract which locks in some
// amount of money to the channel
state.getMultisigContract().getOutput(0).getValue(),
// The channel expires at some offset from when the client's refund transaction becomes
// spendable.
state.getRefundTransactionUnlockTime() + StoredPaymentChannelServerStates.CHANNEL_EXPIRE_OFFSET);
}
@Override
public void paymentIncrease(BigInteger by, BigInteger to) {
log.info("Client {} paid increased payment by {} for a total of " + to.toString(), clientAddress, by);
}
@Override
public void channelClosed(PaymentChannelCloseException.CloseReason reason) {
log.info("Client {} closed channel for reason {}", clientAddress, reason);
try {
p = r.exec("sudo iptables -D internet -t mangle -m mac --mac-source " + clientMac + " -j RETURN");
p.waitFor();
p = r.exec("sudo rmtrack " + clientAddress);
p.waitFor();
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
}